2013-10-28 48 views
1

在請求https://accounts.google.com/o/oauth2/token的令牌時,我花了很多時間浪費了搜索「錯誤請求」的可能原因,於是我決定詢問爲什麼此代碼無法從服務器獲取「不良請求」響應。 ..Google的oauth端點正在返回'錯誤請求'...但爲什麼?

String url = "https://accounts.google.com/o/oauth2/token"; 
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); 
con.setChunkedStreamingMode(0); 
con.setRequestMethod("POST"); 
con.setRequestProperty("Host", "accounts.google.com"); 
con.setRequestProperty("Content-Type", 
     "application/x-www-form-urlencoded"); 
con.setRequestProperty("code", authCode); 
con.setRequestProperty("client_id", 
     "[CLIENT_ID]"); 
con.setRequestProperty("client_secret", "[CLIENT_SECRET"); 
con.setRequestProperty("redirect_uri", 
     "http://localhost:8080/login"); 
con.setRequestProperty("grant_type", "authorization_code"); 

// Send post request 
con.setDoOutput(true); 

我確實必須設置con.setChunkedStreamingMode(0),因爲服務器返回了與內容長度有關的錯誤。

任何想法? 是否有必要將有效載荷放在一行中?怎麼樣?

回答

3

相信對於HTTP 400(錯誤請求)的原因是您發送codeclient_idclient_secretgrant_typeredirect_uri因爲在你需要的HTTP請求頭被髮送它們作爲查詢參數的HTTP的身體POST請求(根據Google OAuth2InstalledApp docs)。

看一看Using java.net.URLConnection to fire and handle HTTP requests是一個關於如何發送HTTP POST的很好的例子。你需要採取codeclient_id等,並把它們寫在身體查詢字符串:

// partial example only: only code and client_id are included 
String query = String.format("code=%s&client_id=%s", code, client_id); 
OutputStream out = con.getOutputStream(); 
out.write(query.getBytes("UTF-8")); 

從谷歌oauth2文檔中,樣品HTTP POST請求可能會是這個樣子:

POST /o/oauth2/token HTTP/1.1 
Host: accounts.google.com 
Content-Type: application/x-www-form-urlencoded 

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu& 
client_id=8819981768.apps.googleusercontent.com& 
client_secret={client_secret}& 
redirect_uri=https://oauth2-login-demo.appspot.com/code& 
grant_type=authorization_code 
+0

我認爲你是對的。嗯,我有另一個問題......只有特定的oauth屬性必須在該查詢字符串上引用?還是我還必須在那裏設置內容類型? – JPCF

+1

只是查詢字符串參數。內容類型需要設置爲HTTP標頭。我已更新我的答案,以顯示Google文檔中的示例HTTP POST。 –

+0

謝謝你!我太吵了! – JPCF

相關問題