Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you exchange Authorization code for a OAuth2 token for google apis in android?

How do you exchange Authorization code for a OAuth2 token for google apis in android? If you go to https://code.google.com/oauthplayground/ you can exchange them, but I need to be able to do it in a android app! Any ideas?

like image 255
William L. Avatar asked Dec 20 '25 11:12

William L.


1 Answers

I found out myself! :)

All you need to do is make a HttpPost to accounts.google.com/o/oauth2/token with the Authorization Code, client id, client secret, redirect_uri and grant type! I added the code to the answer so you can see how to do it exactly! Hope it helps

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("code", "<your_auth_code>"));
pairs.add(new BasicNameValuePair("client_id", "<your_client_id>"));
pairs.add(new BasicNameValuePair("client_secret", "<your_client_secret>"));
pairs.add(new BasicNameValuePair("redirect_uri", "<your_redirect_uri>"));
pairs.add(new BasicNameValuePair("grant_type", "authorization_code")); //Leave this line how it is   
post.setEntity(new UrlEncodedFormEntity(pairs));
org.apache.http.HttpResponse response = client.execute(post);
String responseBody = EntityUtils.toString(response.getEntity());
Log.v("message", responseBody); // That just logs it into logCat
like image 79
William L. Avatar answered Dec 22 '25 01:12

William L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!