21

我一直在使用 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

并产生所需的结果。
但是上面的 POST 请求在 java 中的以下实现会导致一些错误和"invalid_request"
检查下面的代码中的响应并指出这里出了什么问题:(使用 Apache http-components)

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")但这也不起作用。
可能是什么原因?

4

2 回答 2

44

您应该UrlEncodedFormEntity在帖子上使用 not 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);
于 2013-02-25T09:47:52.633 回答
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>
于 2020-01-09T16:59:50.673 回答