Apache HTTPClient POSTs to REST 服务与 cURL 不同



我正在尝试用Apache http client 4.5.5击中REST API。 我可以使用如下cURL成功POSTAPI:

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

但是,当我尝试使用 Apache http 客户端向 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);

我还尝试将身份验证直接添加为标头:

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

也返回一个401 Unauthorized

此外,直接标头变体:

- 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反应。

如何创建一个 Apache http 客户端 POST 请求来执行 cURL 实用程序正在做? cURL 与 Apache 有什么不同 httpclient? 编码(UTF-8(可能是问题所在吗?

其他帖子和文件:

  • cUrl to apache HttpClient
  • 将 curl 转换为 httpclient post
  • Apache HTTP 身份验证

解决方案

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

加上缺少(和必需 - 未记录(标头:

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

最新更新