OAuth2 : exchange access code with a refresh token return an error invalid grant_type

207 views
Skip to first unread message

Akram

unread,
Aug 22, 2012, 12:24:44 PM8/22/12
to google-analytics...@googlegroups.com
I'm using  java HttpURLConnection to make my request
IM sure that my redirect_uri is the same that i put in the registration step, however, i have some doubts about the format ; my redirect_uri is :
http://localhost:8060/myserver/googleapis. I've a error 400 : Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/toke.
 here is my code :

try{
URL googleUrl = new URL("https://accounts.google.com/o/oauth2/token");
String code = "4/FI6f*******************oudcgI";
String clientId = "6********971.apps.googleusercontent.com";
String redirectURI = "http://localhost:8060/myserver/googleapis";

StringBuffer params = new StringBuffer("");
params.append("code=" + code);
params.append("&client_id=" + clientId);
params.append("&client_secret=" + clientSecret);
params.append("&redirect_uri=" + redirectURI);
params.append("&grant_type=authorization_code");

HttpURLConnection connection = (HttpURLConnection) googleUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(params.length()));
connection.setRequestProperty("charset", "utf-8");

DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(params.toString());       
wr.flush();

InputStream st = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(st));
String line;
while ((line = rd.readLine()) != null) {
         System.out.println(line+"\n");
        }
 wr.close();
rd.close();
connection.disconnect();

catch (IOException e){
     System.out.println(e.getMessage()+"\n");
}

Akram

unread,
Aug 23, 2012, 12:53:57 PM8/23/12
to google-analytics...@googlegroups.com
I have to solution for that ;
When you ask for the access code, the response should be redirected to the given URI and the access code should be retrieved from there.
I've got the error because i've requested the access code and retrieved it from the browser (because i,ve not implemented yet the redirect operation in my server). In that case, the redirection operation failed, and as i understood, for web server applications, the flow could not be break.

So, if you get the access code from the redirection URI  operation, exchange it with a refresh token should be done without problems.
Reply all
Reply to author
Forward
0 new messages