如何在Android中为谷歌api交换OAuth2令牌的授权码?如果你去https://code.google.com/oauthplayground/你可以交换它们,但我需要能够在Android应用程序中进行交换!有什么想法吗?
答案 0 :(得分:9)
我发现了自己! :)
您需要做的就是使用授权码,客户端ID,客户端密码,redirect_uri和授权类型将HttpPost发送到accounts.google.com/o/oauth2/token!我将代码添加到答案中,以便您可以看到如何完成!希望它有所帮助
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