制作一个HTTP POST请求到谷歌的Andr​​oid游戏开发者API

问题描述:

我想授权谷歌播放Android开发者的API。我在哪里,我需要做一个HTTP POST请求交换授权$ C $下一个访问令牌,并刷新令牌的步骤。 谷歌给出了下面的例子请求:

I'm trying to authorize the Google Play Android Developer API. I'm at the step where I need to make an HTTP post request to exchange the authorization code for an access token and a refresh token. Google gives the following example request:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code

我很困惑......首先,已安装应用程序(安卓)没有client_secret给出。我创建了一个Web应用程序在谷歌API控制台的同一个项目,这给了我一个client_secret,所以我用了,即使没有Web应用程序。下面code给了我一个invalid_grant错误:

I'm confused... First of all, for an installed application (Android) no client_secret is given. I created a web application for the same project in the Google API Console and this gave me a client_secret, so I used that, even though there is no web application. The following code gives me an "invalid_grant" error:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://accounts.google.com/o/oauth2/token");

try {
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
    nameValuePairs.add(new BasicNameValuePair("code", "CODE"));
    nameValuePairs.add(new BasicNameValuePair("client_id", "CLIENT_ID"));
    nameValuePairs.add(new BasicNameValuePair("client_secret", "CLIENT_SECRET"));
    nameValuePairs.add(new BasicNameValuePair("redirect_uri", "urn:ietf:wg:oauth:2.0:oob"));
    nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpclient.execute(httppost);
    ....

取出client_secret完全给了我一个INVALID_REQUEST错误。

Taking out the client_secret entirely gave me an "invalid_request" error.

这是我如何解决它。我结束了使用Web的applcation。请参阅我的回应here.

This is how I solved it. I ended up using a Web Applcation. See more details in my response here.

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("grant_type",    "refresh_token"));
nameValuePairs.add(new BasicNameValuePair("client_id",      CLIENT_ID));
nameValuePairs.add(new BasicNameValuePair("client_secret",  CLIENT_SECRET));
nameValuePairs.add(new BasicNameValuePair("refresh_token",  REFRESH_TOKEN));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = client.execute(post);