【问题标题】:REST PUT with external file JSON to httpClient Java?带有外部文件 JSON 的 REST PUT 到 httpClient Java?
【发布时间】:2014-11-27 15:44:57
【问题描述】:

例如,我需要翻译一下:

curl -X PUT -u ident:pass -H "Content-Type : application/json" --data-binary @G:\jonJob.json "http://localhost:8080/jobs/"

(这行得通)。

在带有 httpClient 的 java 中。我尝试了很多东西,但没有任何效果.. 有人可以帮帮我吗?

我尝试过的:

public class PostFile {
  @SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {


        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ident", "pass");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();


    HttpPut httppost = new HttpPut("http://localhost:8080/jobs/");
    File file = new File("G:/jsonJob.json");
    HttpEntity httpEntity = MultipartEntityBuilder.create().addBinaryBody("file", file, ContentType.create("application/json"), file.getName()).build();

    httppost.setEntity(httpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpClient.getConnectionManager().shutdown();
  }
}

结果:“HTTP/1.1 415 Not supported type”(不支持的媒体类型)

【问题讨论】:

  • 嗨,谢谢你的回答,我已经用更多信息编辑了我的帖子(抱歉我的英语不好)
  • 不要使用 MME 'multipart' 将 curl @ 替换为帖子。使用 ByteArrayEntity。并获取标头集: request.addHeader("Content-Type", "application/json") ;

标签: java json rest put


【解决方案1】:

对于你的 http req headers -H 你有带有拦截器的 java runnable impl:

公共无效运行(){

CloseableHttpClient httpClient = HttpClients.custom()
        .setConnectionManager(YourConnectionMgr.getInstance())
        .addInterceptorLast(new HttpRequestInterceptor() {
            public void process(
                    final HttpRequest request, 
                    final HttpContext context) throws HttpException, IOException { 

                    if (request.getRequestLine().getMethod() == "POST"){                                
                        request.addHeader("Content-Type", "application/json") ;

请参阅examples here 以找出“connectionManager”

对于简单的身份验证,add this

在内存中映射并发布文件see answer here

注意,你最终会想要某种用于 java 的异步 http 客户端,你可以用谷歌搜索。提供的链接中的 apache 示例主要是阻止网络调用 AFAIK

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2018-08-05
    • 2013-11-13
    • 2014-12-10
    • 1970-01-01
    相关资源
    最近更新 更多