java - 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)可能是问题吗?
其他帖子和文档:
解决方案
您可能错过了“基本”空间,请尝试“基本”
推荐阅读
- node.js - Jasmine 测试错误 - TypeError:无法读取未定义的属性“隐藏”
- python - 在一列内检测行范围内的异常值
- sql-server - 不同数据库中列表表的行数
- python - 用于自动重新排队队列的 Python 数据结构
- r - 栅格计算的条件语句 R
- string - 如何在 Haskell 中替换字符串中的多个字符?
- ios - 如何使用目标 C 进行 json 调用
- r - 如何替换R中的转义字符?
- python - 如何在 python PyQt5 中运行儿童 UI?
- google-cloud-platform - 在 GKE、terraform 与控制台中创建私有集群