2013-03-13 54 views
3

如何获取访问令牌&刷新令牌用于XMPP的谷歌身份验证。我成功获得授权码,但现在我需要获取访问令牌&刷新令牌。但是,当我的要求去做Android中使用下面的代码,我得到的回应: { “错误”:“INVALID_REQUEST” }Google Auth2给出“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方法是正确的这个网址。

+0

您是否尝试过让它成为GET请求并将oauth数据放在标头中?请参阅http://googlecodesamples.com/oauth_playground/ – QVDev 2013-03-13 12:10:30

+0

我收到方法不允许的错误。当我使用GET方法。 – 2013-03-14 06:10:02

+0

做了一些简单的工作请求和代码请求。结果他们是不同的,实际上也提供了另一个回应。你能否更详细地解释你在做什么,你从哪里获得请求以及为什么要这样构建请求?任何参考我可以看看? – QVDev 2013-03-14 08:27:15

回答

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. 
    } 
+0

非常不错+1此 – QAMAR 2013-04-05 08:57:21

+0

做同样的事情,但是不像@RajaReddy那样成功。我必须将HttpClient连接到一些webview吗?我的安装应用程序的客户端ID设置也一样。此代码可以像这样运行,并返回access_token refresh_token – Erik 2013-04-18 12:32:48

+0

嗨,不需要将此附加到一个Web视图。这只是一个普通的HTTP客户端请求。上面附上的代码应该可以在requestBody中附加wright证书。如果不是,请发布您的调试信息。 – QVDev 2013-04-18 12:38:52

相关问题