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; builder1.addFormDataPart("file", ((File) value).getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)); } else { 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
| 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)); }
|