I got the authorization code following this document. But when I tried to get access token, I always got errors. Can anyone help me ?
public String AccessToken()
{
String accessToken = "";
StringBuilder strBuild = new StringBuilder();
String authURL = "https://accounts.google.com/o/oauth2/token?";
String code = "4/SVisuz_x*********************";
String client_id = "******************e.apps.googleusercontent.com";
String client_secret = "*******************";
String redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
String grant_type="authorization_code";
strBuild.append("code=").append(code)
.append("&client_id=").append(client_id)
.append("&client_secret=").append(client_secret)
.append("&redirect_uri=").append(redirect_uri)
.append("&grant_type=").append(grant_type);
System.out.println(strBuild.toString());
try{
URL obj = new URL(authURL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Host", "www.googleapis.com");
//BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
//bw.write(strBuild.toString());
//bw.close();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(strBuild.toString());
wr.flush();
wr.close();
//OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
System.out.println(con.getResponseCode());
System.out.println(con.getResponseMessage());
} catch (Exception e)
{
System.out.println("Error.");
}
return "";
}
when I ran this code, the output is:
400
Bad Request
You are not using the right endpoint. Try to change the
authURL
tohttps://www.googleapis.com/oauth2/v4/token
From the documentation:
The actual request might look like the following:
Reference https://developers.google.com/identity/protocols/OAuth2InstalledApp#handlingtheresponse
Firstly, you must look this page :
https://developers.google.com/gmail/api/auth/web-server#create_a_client_id_and_client_secret
The value you see in the query parameter code is a string you have to post to google in order to get the access token.
After the web server receives the authorization code, it may exchange the authorization code for an access token and a refresh token. This request is an HTTPS POST to the URL https://www.googleapis.com/oauth2/v3/token POST /oauth2/v3/token HTTP/1.1 content-type: application/x-www-form-urlencoded
code=4/v4-CqVXkhiTkn9uapv6V0iqUmelHNnbLRr1EbErzkQw#&redirect_uri=&client_id=&scope=&client_secret=************&grant_type=authorization_code https://developers.google.com/identity/protocols/OAuth2WebServer
Refer : https://developers.google.com/android-publisher/authorization
You already have authorization code that is called "refresh token". Please keep it in safe place. You can use "refresh token" to generate "access token".
To get "access token", please make a post request to following URL
https://accounts.google.com/o/oauth2/token
Parameters:
where "grant_type" should be "refresh_token"
We are using PHP to do same, here is PHP's code for your reference
Hope it will help you.
Ans: As per your following tutorial, you are using
OAuth 2.0
. So there is a basic pattern for accessing a Google API usingOAuth 2.0
. It follows 4 steps:For details, you can follow the tutorial - Using OAuth 2.0 to Access Google APIs
You have to visit the Google Developers Console to obtain OAuth 2.0 credentials such as a
client ID
andclient secret
that are known to both Google and your applicationRoot Cause Analysis:
Issue-1:
After studying your code, some lacking are found. If your code runs smoothly, then the code always give an empty string. Because your
AccessToken()
method always returnreturn "";
Issue-2:
Your try catch block is going exception block. Because, it seems that you have not completed your code properly. You have missed
encoding
as well as usingJSONObject
which prepares the access token. So it is giving output asSolution:
I got that your code is similar with this tutorial
As your code needs more changes to solve your issue. So I offer you to use LinkedHashMap or ArrayList. Those will provide easier way to make solution. So I give you 2 sample code to make your life easier. You can choose any of them. You need to change
refresh_token, client id, client secret and grant type
as yours.Resource Link:
Unable to get the subscription information from Google Play Android Developer API
Using java.net.URLConnection to fire and handle HTTP requests
How to send HTTP request GET/POST in Java
Hope that, this
samples
andresource link
will help you to solve your issue and get access ofaccess token
.What is 400 bad request?
Ans: It indicates that the query was invalid. Parent ID was missing or the combination of dimensions or metrics requested was not valid.
Recommended Action: You need to make changes to the API query in order for it to work.
Why token expires? What is the limit of token?
A token might stop working for one of these reasons:
revoked
access.six months
.user changed passwords
and the token contains Gmail, Calendar, Contacts, or Hangouts scopes.exceeded a certain number of token requests
.There is
currently a limit of 25 refresh tokens per user account per client
. If the limit is reached, creating a new token automatically invalidates the oldest token without warning. This limit does not apply to service accounts.Which precautions should be followed?
Precautions - 1:
Precautions - 2:
Precautions - 3:
For me your request is fine, I tried it using Curl, I also get a 'HTTP/1.1 400 Bad Request' with the reason why it failed 'invalid_grant' :
I receive (HTTP/1.1 400 Bad Request) :
Now using HttpClient from Apache :
I see in my console :
Are you sure the code you are using is still valid ? Can you try with a new one ?
I think I understand what's wrong:
as @newhouse said, you should POST to
https://www.googleapis.com/oauth2/v4/token
and nothttps://accounts.google.com/o/oauth2/token
(@newhouse I gave you a +1 :) )(
https://www.googleapis.com/oauth2/v4/token
is for getting theauthorization_code
andhttps://accounts.google.com/o/oauth2/token
is for getting thecode
).You can't use the same
code
more than once.Everything else seems in order so, if you keep getting 400, you are probably trying to use the
code
you got more than one time (then you'll get 400 every time, again and again).* You should also lose the
con.setRequestProperty("Host", "www.googleapis.com");