Apache HTTPClient POST 到 REST 服务的方式与 cURL 不同

Apache HTTPClient POSTs to REST service differently than cURL

我正在尝试用 Apache http client 4.5.5 命中 REST API。我可以像这样使用 cURL 成功 POST 到 API:

curl -X POST --user username:password  --header "Content-Type: application/json" --data "@/path/to/file.json" https://some.restfulapi.com/endpoint

然而,当我尝试使用 Apache http 客户端 POST 到 API 时,它总是失败并显示 HTTP 错误代码:401 Unauthorized 当使用相同的凭据时:

HttpClient httpclient = new DefaultHttpClient();

CredentialsProvider credentialsPovider = new BasicCredentialsProvider();
credentialsPovider.setCredentials(new AuthScope(request.getHost(), 443),  new UsernamePasswordCredentials(user, password));
                

HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsPovider);


HttpPost httppost = new HttpPost(request.getHost()); 


// append headers
for(Header header : request.getHeaders()){
    httppost.addHeader(header.getKey(), header.getValue());
}
                
if(body_entity.length()>0){
    // append the  data to the post
    StringEntity stringentity = new StringEntity(body_entity, HTTP.UTF_8);
    stringentity.setContentType(content_type);
    httppost.setEntity(stringentity);                                           
}


HttpResponse response = httpclient.execute(httppost, context);

我也试过直接将身份验证添加为 header:

String encoding = Base64.getEncoder().encodeToString((user + ":" + password);
httppost.addHeader("Authentication", encoding);

returns一个401 Unauthorized也是。

此外,直接 header 变体:

- httppost.addHeader("user", "Basic " + encoding);
- httppost.addHeader("Authentication", "Basic " + encoding);
- httppost.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password), "UTF-8", false));

所有结果都在 400 Bad request 响应中。

将 HttpClientBuilder 与 CredentialsProvider 结合使用

HttpClientBuilder clientbuilder = HttpClients.custom();
clientbuilder = clientbuilder.setDefaultCredentialsProvider(credentialsPovider);
httpclient = clientbuilder.build();

也会导致 400 Bad request 响应。

How do I create an Apache http client POST request that does what the cURL utility is doing? What is cURL doing differently than Apache httpclient? Might the encoding (UTF-8) be the issue?

其他帖子和文档:

您可能错过了 space“基本”,尝试“基本”

解决方案

httppost.addHeader("Authorization", "Basic "+Base64.getEncoder().encodeToString("user:password".getBytes()));

加上缺失的(和必需的 - 未记录的)header:

httppost.addHeader("Content-Length", json.toString().length);