Java使用httpClient进行文件上传

Java使用httpClient进行文件上传

使用场景:服务端使用InputStream来接收文件

客户端使用post请求

fileNameWithSuffix表示带后缀的文件名,例如test.txt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public String postFile(String url, String token, String fileNameWithSuffix, InputStream inputStream) {

HttpPost httpPost = new HttpPost(url);

// 设置请求头
httpPost.setHeader("Authorization", token);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", inputStream, ContentType.create("multipart/form-data"), fileNameWithSuffix);

HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();

try {
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

if (null != httpResponse) {
HttpEntity responseEntity = httpResponse.getEntity();
String responseStr = EntityUtils.toString(responseEntity, "UTF-8");
log.info("打印响应信息:{}", responseStr);
}
} catch (Exception e) {
log.error(e.toString(),e);
}

return null;
}
Author: Aaron
Link: https://xjsir.cn/2023/03/05/Java使用httpClient进行文件上传/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.