3

如何获取 XMPP 谷歌身份验证的访问令牌和刷新令牌。我成功获得了授权码,但现在我需要获取访问令牌和刷新令牌。但是当我在 Android 中使用下面的代码发出请求时,我得到了响应:{“error”:“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 是正确的。

4

1 回答 1

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.
    }
于 2013-03-14T11:02:31.637 回答