【问题标题】:How to upload a file using Apache HttpPost如何使用 Apache HttpPost 上传文件
【发布时间】:2016-02-05 15:56:17
【问题描述】:

我有一个这样的 curl 调用:

curl -i -X POST -H "Content-Type: multipart/form-data" -F "file=@data_test/json_test.json" http://domain.com/api/upload_json/

我需要做的只是这个调用的 Java 实现。我已经编写了这段代码,但是出现在服务器上的文件似乎为空。

public static void uploadJson(String url, File jsonFile) {
    try {
        HttpPost request = new HttpPost(url);
        EntityBuilder builder = EntityBuilder
                .create()
                .setFile(jsonFile)
                .setContentType(ContentType
                        .MULTIPART_FORM_DATA)
                .chunked();
        HttpEntity entity = builder.build();
        request.setEntity(entity);
        HttpResponse response = getHttpClient().execute(request);
        logger.info("Response: {}", response.toString());
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}

构建此请求的正确方法是什么?

【问题讨论】:

    标签: java curl apache-httpclient-4.x


    【解决方案1】:
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .build();
    
    HttpEntity requestEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file", new File("data_test/json_test.json"))
            .build();
    HttpPost post = new HttpPost("http://domain.com/api/upload_json/");
    post.setEntity(requestEntity);
    try (CloseableHttpResponse response = httpClient.execute(post)) {
        System.out.print(response.getStatusLine());
        EntityUtils.consume(response.getEntity());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-04
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      相关资源
      最近更新 更多