其他分享
首页 > 其他分享> > 向Google Play Android开发者API发出HTTP发布请求

向Google Play Android开发者API发出HTTP发布请求

作者:互联网

我正在尝试授权Google Play Android开发人员API.我现在需要发出一个HTTP发布请求,以将访问令牌和刷新令牌的授权代码交换. Google给出以下示例请求:

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

我很困惑…首先,对于已安装的应用程序(Android),没有提供client_secret.我在Google API控制台中为同一项目创建了一个Web应用程序,这给了我一个client_secret,所以即使没有Web应用程序,我也使用了它.以下代码给我一个“ invalid_grant”错误:

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”错误.

解决方法:

这就是我解决的方法.我最终使用了Web应用程序.在我的回复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);

标签:api,google-play,httprequest,http-post,android
来源: https://codeday.me/bug/20191031/1979423.html