I have the following on a web servlet:
EDITED:
public String tryGoogleAuthentication(String auth_token){
HttpURLConnection connection = null;
try {
//connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2v1/tokeninfo?access_token={"+auth_token+"}")).openConnection();
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/user info")).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer {"+auth_token+"}");
connection.setRequestProperty("Host", "googleapis.com");
//read response
String response = fromInputStreamToString(connection.getInputStream());
System.out.println(response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return CONST.STATUS_OK;
}
In android:
private void googleAuthenticate(){
try {
mOAauthHelper = new OAuthHelper("something.net", "xxxxxxxxxx",
"https://www.googleapis.com/auth/userinfo.profile", "alex://myScheme");
String uri = mOAauthHelper.getRequestToken();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(uri)));
//Intent i = new Intent(this, GoogleOAUTHActivity.class);
//i.putExtra(GoogleOAUTHActivity.GOOGLE_OAUTH_ENDPOINT_KEY, uri);
//startActivity(i);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthNotAuthorizedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
failedAuthenticatingAtGoogle();
}
}
and
#Override
protected void onNewIntent(Intent intent) {
//super.onNewIntent(intent);
Uri uri = intent.getData();
String oauthToken = uri.getQueryParameter("oauth_token");
String oauthVerifier = uri.getQueryParameter("oauth_verifier");
if(oauthToken != null){
authorizeGoogleSessionToServer(oauthToken);
}
}
After this, I send the request token to my servlet where I tried to get user profile, but with no success.
Could you please tell me what's wrong and why I'm getting error 400 from google?
Thanks.
Unfortunately, I can see a few issues with this already
you should never have curly braces in your URL or even in the Bearer header as stated in the draft.
connection = (HttpURLConnection) new URL(("https://www.googleapis.com/oauth2/v1/userinfo?access_token={"+auth_token+"}")).openConnection()
400 means that you're missing something in your request, there is probably more information about it in the same response as specific error node.
Finally, take care, oauth_verifier param is from OAuth 1.
I suggest you test your request URL's, using the Google OAuth2 playground
Good luck!
Related
I have such an OkHttp code to retreive data from OpenWeather API:
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new okhttp3.Request.Builder().url(url).build();
AsyncTask.execute(() -> {
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
if(response.code() == 200) {
Log.d("weather", "200");
JSONArray array;
try {
JSONObject mObj = new JSONObject(response.body().string());
array = mObj.getJSONArray("weather");
widgetView.setTextViewText(R.id.weatherTextView, array.getJSONObject(0).getString("main"));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
It's located in my Widget class in void updateWidget, which is called from onUpdate() void. But the problem is that this OkHttp code just doesn't get executed.
What can cause this problem?
So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();
class background_thread extends AsyncTask<String ,String , Boolean > {
protected Boolean doInBackground(String... params) {
String UR = "127.0.0.1/abc/index.php";
try {
URL url = new URL(UR);
} catch(MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
}
}
When I use the above code, in the HttpURLConnection the url turns red and Android Studio is showing an error can not resolve symbol url. What's wrong with the code?
I encountered the same problem. Just do:
import java.net.URL;
Put the line which is openning connection inside of try clause:
try {
URL url = new URL(UR);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Do something...
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
It is because the valiable url is a local one which is valid only inside the try clause.
Or declair the url outside of the try clause:
URL url;
try {
url = new URL(UR);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Do something...
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
With Java 7+, we can use the AutoClosable feature:
URL url;
try {
url = new URL(UR);
} catch(MalformedURLException e) {
e.printStackTrace();
}
try (HttpURLConnection conn = (HttpURLConnection) url.openConnection())
// Do something...
} catch (IOException e) {
e.printStackTrace();
}
Sometimes you need a asimple 'gradlew clean'
"Click" on "Build"->"Clean Project" and that will perform a gradle clean
Or:
"Tools" -> "Android" -> "Sync Project with Gradle Files"
Adding
import java.net.MalformedURLException;
solve the missing resolve symbol.
You must of course have this too:
import java.net.URL;
I am trying to connect to a website where the site database adds a name to a list based on the url you connect with. I can't connect. The site works and I can access it in a browser. The error is an IOException.
if ((Boolean) value)
{
System.out.println("setValue");
try
{
URL myURL = new URL("http://app.bannervision.tv/api/add/" + data.name.get(row));
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e)
{
System.out.println("MalformedURLException");
// ...
}
catch (IOException e)
{
System.out.println("IOException");
System.out.println("http://app.bannervision.tv/api/add/" + data.name.get(row));
// openConnection() failed
// ...
}
}
I'm new to mobile apps development. I'm developing a blackberry application which reads tweets from the user's timeline. So far I managed to get the OAuth access token. The problem happens when I try to use this access token to read the tweets I get a 401 response with a message "Unauthorized". I'm not using any libraries I'm doing everything on my own. Could anyone help me with this?
Thanks,
Here's the code:
HttpConnectionFactory factory = new HttpConnectionFactory( url,
HttpConnectionFactory.TRANSPORT_WIFI |
HttpConnectionFactory.TRANSPORT_WAP2 |
HttpConnectionFactory.TRANSPORT_BIS |
HttpConnectionFactory.TRANSPORT_BES |
HttpConnectionFactory.TRANSPORT_DIRECT_TCP);
httpConn = factory.getNextConnection();
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
httpConn.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Length", Integer.toString(header.getBytes().length));
os = httpConn.openOutputStream();
os.write(header.getBytes());
os.close();
os = null;
input = httpConn.openDataInputStream();
int resp = httpConn.getResponseCode();
// Dialog.alert(httpConn.getDate()+" : "+System.currentTimeMillis());
if (resp == HttpConnection.HTTP_OK) {
XMLReader parser;
try {
parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(this);
parser.parse(new InputSource(input));
for(int i=0 ; i<2 ; i++)
{
tweets.addElement( parser.getProperty("text").toString());
Dialog.alert(parser.getProperty("text").toString());
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dialog.alert("your tweet was posted successfully :)");
}
Dialog.alert(httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
return (httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
} catch (IOException e) {
return "exception";
} catch (NoMoreTransportsException nc) {
return "noConnection";
} finally {
try {
httpConn.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not an expert in OAuth, however just a note:
This:
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
and this:
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
are mutually exclusive things. You are posting data to server, so it should be a POST (not GET).