如何在 android 中为 google apis 交换 OAuth2 令牌的授权码?如果你去https://code.google.com/oauthplayground/你可以交换它们,但我需要能够在一个安卓应用程序中做到这一点!有任何想法吗?
问问题
4152 次
1 回答
10
我自己发现了!:)
您需要做的就是使用授权码、客户端 ID、客户端密码、redirect_uri 和授权类型向 accounts.google.com/o/oauth2/token 发送 HttpPost!我将代码添加到答案中,这样您就可以看到如何准确地做到这一点!希望能帮助到你
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
于 2012-06-19T01:08:41.923 回答