Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 谷歌';s oauth端点正在返回一个';错误的请求';。。。但是为什么呢?_Java_Oauth_Oauth 2.0_Httpsurlconnection - Fatal编程技术网

Java 谷歌';s oauth端点正在返回一个';错误的请求';。。。但是为什么呢?

Java 谷歌';s oauth端点正在返回一个';错误的请求';。。。但是为什么呢?,java,oauth,oauth-2.0,httpsurlconnection,Java,Oauth,Oauth 2.0,Httpsurlconnection,在上请求令牌时,为了寻找“错误请求”的可能原因,我花费了大量时间在谷歌上搜索,然后我决定问为什么这段代码只能从服务器上获得“错误请求”响应 String url = "https://accounts.google.com/o/oauth2/token"; HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setChunkedStreamingMode(0); con.setRequestMethod(

在上请求令牌时,为了寻找“错误请求”的可能原因,我花费了大量时间在谷歌上搜索,然后我决定问为什么这段代码只能从服务器上获得“错误请求”响应

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\u id
client\u secret
grant\u type
redirect\u uri
作为HTTP请求头发送,您需要将它们作为HTTP POST请求体中的查询参数发送(根据协议)

请看一个关于如何发送HTTP POST的好例子。您需要获取
code
client\u 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

我想你是对的。嗯,我还有一个问题。。。在该查询字符串上只需引用特定的oauth属性?或者我必须在那里设置内容类型吗?只设置查询字符串参数。内容类型需要设置为HTTP头。我已经更新了我的答案,以显示谷歌文档中的HTTP帖子示例。