我有这样的卷毛电话:
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());
}
}
构建此请求的正确方法是什么?
答案 0 :(得分:6)
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());
}