Google Auth2为获取访问令牌提供“invalid_request”响应&刷新令牌

时间:2013-03-13 11:42:30

标签: android http-post google-authentication

如何获取访问令牌&为XMPP的Google身份验证刷新令牌。我成功获得了授权码,但现在我需要获取访问令牌&刷新令牌。但是当我在Android中使用下面的代码执行请求时,我得到了响应: {   "错误":" INVALID_REQUEST" }

HttpPost request = new HttpPost("https://accounts.google.com/o/oauth2/token" );         
json.put("client_id", "128232338269.apps.googleusercontent.com" );
json.put("client_secret", "eufZ8Rmjsk1MaADYsHYW" );
json.put("redirect_uri", "urn:ieadsdg:oauth:2.0:oob");
json.put("code", res_code);
json.put("grant_type", "authorization_code");

StringEntity se = new StringEntity(json.toString());

Log.i(TAG, "JSON********" +json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
request.setEntity(se);

/* Checking response */  
response = client.execute(request); 

但是我收到了该代码的错误。 Response = { "error" : "invalid_request" }

这里有什么问题。 HttpPost方法对于此URL是正确的。

1 个答案:

答案 0 :(得分:3)

聊天后我们发现了问题所在。有效负载错误,内容类型设置错误。以下代码是解决方案:

    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost("https://accounts.google.com/o/oauth2/token" );
    request.setHeader("Content-type", "application/x-www-form-urlencoded");

    //Please make this custom with you're credentials
    String requestBody = "code=123123132&client_secret=eufFgyAZ8Rmjsk1MaADYsHYW&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code&client_id=128169428269.apps.googleusercontent.com";

    try {
        request.setEntity(new StringEntity(requestBody));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

    /* Checking response */
    try {
        HttpResponse response = client.execute(request);
        String results = "ERROR";
        results = EntityUtils.toString(response.getEntity());
        Log.d("STACK", "Response::" + results);
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }