简体   繁体   中英

Invalid request when trying to obtain access token for Google API

I am trying to obtain an access token from a Java desktop/standalone application using Apache Http:

    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));

The request URL is:

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

The content is:

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

and I get:

{
  "error" : "invalid_request"
}

I read the other similar SO questions, but it did not solve my issue.

What am I doing wrong?

My mistake. Actually below code

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

should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM