尝试获取Google API的访问令牌时出现无效请求

时间:2012-12-03 19:06:09

标签: java request google-api

我正在尝试使用Apache Http:

从Java桌面/独立应用程序获取访问令牌
    StringBuilder sb = new StringBuilder();
    sb.append("code").append('=').append(authorization_code)
      .append('&').append("client_id").append('=').append(client_id)
      .append('&').append("client_secret").append('=').append(client_secret)
      .append('&').append("redirect_uri").append('=').append("urn:ietf:wg:oauth:2.0:oob2")
      .append('&').append("grant_type").append('=').append("authorization_code");

    HttpPost httppost
        = new HttpPost("https://accounts.google.com/o/oauth2/token");
    httppost.setEntity(new StringEntity(sb.toString()));

    System.out.println(httppost.getURI());

    System.out.println(new String(
            EntityUtils.toByteArray(httppost.getEntity())));
    httppost.getEntity().getContent();

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse resp = httpclient.execute(httppost);

    byte[] ba = EntityUtils.toByteArray(resp.getEntity());
    System.out.println(new String(ba));

请求网址为:

https://accounts.google.com/o/oauth2/token

内容为:

code=4/uktjFRIoKS-VTwADJjO6vSYV3ZyU.Qop5zb7BIj0bOl05ti8ZT3bH57rDdgI
&client_id=128871852795.apps.googleusercontent.com
&client_secret=***********************
&redirect_uri=urn:ietf:wg:oauth:2.0:oob2
&grant_type=authorization_code

我得到了:

{
  "error" : "invalid_request"
}

我读了其他类似的SO问题,但它没有解决我的问题。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我的错误。实际上是下面的代码

&redirect_uri=urn:ietf:wg:oauth:2.0:oob2

应该是

&redirect_uri=urn:ietf:wg:oauth:2.0:oob