I am trying to authenticate my application to Google contacts API. I have gone though the first step in the Oauth2 flow and have an authorization code. I am trying to exchange this code for an access token and refresh token, but when i try to get Token from googleapis.com/oauth2/v4/token receive with
response : "invalid_grant" "Bad request" Error 400.
My code
try
{
Map<String,Object> params = new LinkedHashMap<>();
params.put("grant_type","authorization_code");
params.put("code", authCode);
params.put("client_id",CLIENTE_ID);
params.put("client_secret",CLIENTE_ID_SECRETO);
params.put("redirect_uri","http://localhost:8080/conob/api2/contatos/insert");
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet())
{
if(postData.length() != 0){
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(),"UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()),"UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
URL url = new URL("https://www.googleapis.com/oauth2/v4/token");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Length", postData.toString().length() + "");
con.getOutputStream().write(postDataBytes);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine()){
buffer.append(line);
}
JSONObject json = new JSONObject(buffer.toString());
String accessToken = json.getString("access_token");
return accessToken;
} catch (Exception e) {
reader = new BufferedReader(new InputStreamReader(con.getErrorStream()));
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine()){
buffer.append(line);
}
System.out.println(buffer.toString());
System.out.println(e.toString());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
Parameters output:
grant_type=authorization_code&code=AUTHORIZATION_CODE&client_id=CLIENTE_ID&client_secret=CLIENTE_SECRET&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fconob%2Fapi2%2Fcontatos%2Finsert
I'm searching for many hours in many forums but not conclude a solution for my problem.
Basically, my app needs to insert new contact on a google accounts in company intranet.
My question is what the response is "invalid_grant"?
Good code and thanks since now;