Java使用OKHttp进行文件上传

Java使用OKHttp进行文件上传

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

客户端使用post请求

headerMap用于存放请求头信息

paramsMap用于存放文件字符串参数

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public String postFile(String url, HashMap<String, String> headerMap, HashMap<String, Object> paramsMap) throws IOException{

MultipartBody.Builder builder1 = new MultipartBody.Builder();
builder1.setType(MultipartBody.FORM);
for (Map.Entry<String, Object> stringObjectEntry : paramsMap.entrySet()) {
String key = stringObjectEntry.getKey();
Object value = stringObjectEntry.getValue();
if (value instanceof File) {//如果请求的值是文件
File file = (File) value;
//MediaType.parse("application/octet-stream")以二进制的形式上传文件
builder1.addFormDataPart("file", ((File) value).getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
} else {//如果请求的值是string类型
builder1.addFormDataPart(key, value.toString());
}
}

Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(url);

// 添加请求头
if(CollectionUtil.isNotEmpty(headerMap)){
Set<String> keys = headerMap.keySet();
for (String key : keys) {
String val = headerMap.get(key);
requestBuilder.addHeader(key, val);
}
}
requestBuilder.post(builder1.build()).url(url);
Request request = requestBuilder.build();

try (Response response = client.newCall(request).execute()) {
ResponseBody responseBody = response.body();
if (Objects.isNull(responseBody)) {
throw new RuntimeException("响应体为空");
}
String strResponse = responseBody.string();
log.info("打印响应参数:{}", strResponse);
return strResponse;
} catch (Exception e) {
log.error(e.toString(),e);
}

}

客户端支持上传多个文件,paramsMap中的value设置为File类型的文件即可

1
2
3
4
5
6
7
8
// 假设现在有多个list:List<File> files
Map<String, Object> paramsMap = new HashMap<>();
// 字符串类型参数正常设置即可
paramsMap.put("StringKey", "StringValue");
// 文件类型参数设置方式如下:
for(int i = 0; i < files.size(); i++) {
paramsMap.put("file"+i, files.get(i));
}
Author: Aaron
Link: https://xjsir.cn/2023/03/05/Java使用OKHttp进行文件上传/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.