我一直在使用java处理Google OAuth 2.0,并在实施过程中遇到了一些未知错误 以下用于POST请求的CURL工作正常:
curl -v -k --header "Content-Type: application/x-www-form-urlencoded" --data "code=4%2FnKVGy9V3LfVJF7gRwkuhS3jbte-5.Arzr67Ksf-cSgrKXntQAax0iz1cDegI&client_id=[my_client_id]&client_secret=[my_client_secret]&redirect_uri=[my_redirect_uri]&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
并产生所需的结果。
但是以下在java中执行上面的POST请求会导致一些错误和"invalid_request"
中的响应
检查以下代码并指出这里出错:(使用Apache http组件)
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
HttpParams params = new BasicHttpParams();
params.setParameter("code", code);
params.setParameter("client_id", client_id);
params.setParameter("client_secret", client_secret);
params.setParameter("redirect_uri", redirect_uri);
params.setParameter("grant_type", grant_type);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setParams(params);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(post);
为每个参数尝试URLEncoder.encode( param , "UTF-8")
,但这也不起作用。
可能是什么原因?
答案 0 :(得分:22)
你应该在帖子上使用UrlEncodedFormEntity
而不是setParameter。
它也为你处理Content-Type: application/x-www-form-urlencoded
标题。
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("code", code));
nvps.add(new BasicNameValuePair("client_id", client_id));
nvps.add(new BasicNameValuePair("client_secret", client_secret));
nvps.add(new BasicNameValuePair("redirect_uri", redirect_uri));
nvps.add(new BasicNameValuePair("grant_type", grant_type));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(post);
答案 1 :(得分:1)
用于发送UrlEncoded请求的更为通用和统一的方法:
@SneakyThrows
public String postUrlEncoded(String context, Map<String, String> body) {
List<NameValuePair> nameValuePairs = body.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
HttpResponse response = Request.Post(baseUrl + context)
.bodyForm(nameValuePairs)
.execute().returnResponse();
return EntityUtils.toString(response.getEntity());
}
Ps:它需要流畅的Apache HTTP客户端。 Pom依赖项:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>${fluent-hc.version}</version>
</dependency>