2013-03-13 53 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

相關問題