Google的oauth端点正在返回“错误请求”……但为什么呢?

在https://accounts.google.com/o/oauth2/token请求代币时,在搜索“错误请求”的可能原因后浪费了大量时间,我决定问为什么此代码无法获取只是来自服务器的“错误请求”响应……

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)因为服务器返回了与内容长度相关的错误。

有任何想法吗? 是否有必要将有效载荷放在一条线上? 怎么样?

我相信HTTP 400(错误请求)的原因是您发送codeclient_idclient_secretgrant_typeredirect_uri作为HTTP请求标头,您需要将它们作为HTTP POST请求正文中的查询参数发送(根据到Google OAuth2InstalledApp文档 )。

看一下使用java.net.URLConnection来触发和处理HTTP请求 ,以获得如何发送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")); 

在Google 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