此 POST 请求实现有什么问题?

我一直在使用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请求会导致一些错误,
检查以下代码中的响应并指出此处的错误:(使用了Apache http-components)"invalid_request"

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")


答案 1

你应该在帖子上使用不设置参数。它也为您处理标头。UrlEncodedFormEntityContent-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);

答案 2

发送 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>