提问者:小点点

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


我正在尝试使用Apache http Client4.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客户端发布API时,它总是失败,http错误代码为:401 authorize当使用相同的凭据时:401 authorize:

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.setHeader(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("user", "Basic " + encoding);

导致400错误请求响应。

和变体:

- httppost.addHeader("Authentication", "Basic " + encoding);
- httppost.addHeader("user", encoding);
- httppost.addHeader("Authentication", encoding);

包括:

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

还有400错误请求响应。

使用带有CredentialsProvider的HttpClientBuilder

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

但这也会导致400坏请求响应。

如何创建一个Apache http客户端POST请求来执行cURL实用程序正在执行的操作? cURL与Apache HttpClient有什么不同?

其他员额和文件:

  • 卷曲到apache HttpClient
  • 将curl转换为httpclient Post
  • Apache HTTP身份验证

共1个答案

匿名用户

您可能漏掉了一个空格“basic”,请尝试“basic”