在 https://accounts.google.com/o/oauth2/token 请求 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(错误请求)的原因是您正在发送 code
、client_id
、client_secret
、grant_type
和 redirect_uri
作为 HTTP 请求 header ,您需要将它们作为 HTTP POST 请求正文中的查询参数发送(根据 Google OAuth2InstalledApp docs )。
看看Using java.net.URLConnection to fire and handle HTTP requests有关如何发送 HTTP POST 的一个很好的示例。您需要获取 code
、client_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
关于java - Google 的 oauth 端点返回 'Bad Request' ...但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19625621/