首页 > 解决方案 > Apache HTTPClient POST 到 REST 服务的方式与 cURL 不同

问题描述

我正在尝试REST API使用Apache http client 4.5.5. 我可以像这样成功POST地使用 API cURL

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

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

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

也返回 a 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响应。

如何创建执行 cURL 实用程序正在执行的操作的 Apache http 客户端 POST 请求?cURL 与 Apache httpclient 有何不同?编码(UTF-8)可能是问题吗?

其他帖子和文档:

标签: javahttpclientjira-rest-api

解决方案


您可能错过了“基本”空间,请尝试“基本”


推荐阅读