gpt4 book ai didi

java - 如何使用 Apache HttpPost 上传文件

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:23:22 25 4
gpt4 key购买 nike

我有一个像这样的 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());
}
}

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

最佳答案

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

关于java - 如何使用 Apache HttpPost 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35228317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com