Java 如何使用ApacheHttpPost上传文件

Java 如何使用ApacheHttpPost上传文件,java,curl,apache-httpclient-4.x,Java,Curl,Apache Httpclient 4.x,我有这样一个卷发电话: 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) { tr

我有这样一个卷发电话:

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());
    }
}
构建此请求的正确方法是什么

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