java - Google 的 oauth 端点返回 'Bad Request' ...但为什么呢?

标签 java oauth oauth-2.0 httpsurlconnection

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(错误请求)的原因是您正在发送 codeclient_idclient_secretgrant_type redirect_uri 作为 HTTP 请求 header ,您需要将它们作为 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"));

根据 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/

相关文章:

java - JUnit 比较集合中的对象,但包含对象中的指定字段除外

java - 使用流映射 java 8 转换另一个列表

javascript - 如果用户未登录 Facebook,则 FB.getLoginStatus 不会触发

android - 在 Android 客户端/服务器应用程序中实现 Google 登录

android - Android 中的 QuickBook Online API 集成 oauth 问题

java - 获取授权码后使用 Google Android Auth 2.0 HTTP post 请求进行注册

java - 为什么我的 oauth2 配置没有使用我的自定义 UserService?

java - 使用一条语句插入多行与在mysql中批量插入

java - 读取文件信息并将其放入数组列表中

oauth - 如何使用 Bing 的搜索 API?