/**
* 使用HttpClient4.5 post提交multipart/form-data数据实现多文件上传
* @param url 请求地址
* @param multipartFiles post提交的文件列表
* @param fileParName fileKey
* @param params 附带的文本参数
* @param timeout 请求超时时间(毫秒)
* @return
* @author lingtong`
* @date 2019年1月21日 上午11:36:15
*/
public static Map<String, String> httpPostRequest2(String url, List<MultipartFile> multipartFiles, String fileParName,
Map<String, Object> params, int timeout) {
Map<String, String> resultMap = new HashMap<String, String>();
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("sign","86358999");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = null;
MultipartFile multipartFile = null;
if (multipartFiles != null){
for (int i = 0; i < multipartFiles.size(); i++) {
multipartFile = multipartFiles.get(i);
fileName = multipartFile.getOriginalFilename();
builder.addBinaryBody(fileParName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
}
}
//决中文乱码
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
for (Map.Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null)
continue;
// 类似浏览器表单提交,对应input的name和value
builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
// 设置连接超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
httpPost.setConfig(requestConfig);
HttpEntity responseEntity = response.getEntity();
resultMap.put("scode", String.valueOf(response.getStatusLine().getStatusCode()));
resultMap.put("data", "");
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
resultMap.put("data", result);
}
} catch (Exception e) {
resultMap.put("scode", "error");
resultMap.put("data", "HTTP请求出现异常: " + e.getMessage());
Writer w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
//logger.error("HTTP请求出现异常: " + w.toString());
System.out.println("HTTP请求出现异常: " + w.toString());
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultMap;
}
public static void main(String[] args)throws Exception{
Map<String, Object> data = new HashMap<>();
/*data中请求需要的参数*/
data.put("account", "szsdtjtfafa");//账号
data.put("password", "Mima12345");//密码
//导入需要上传的文件
File file = new File("C:\\Users\\Thinkpa\\Desktop\\161616.jpg");
FileItem fileItem = dataFormat(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
List<MultipartFile> list = new ArrayList();
list.add(multipartFile);
Map<String, String> resultDataMap = httpPostRequest2("xxx/noticeInterface/save",list, "files", data, -1);
System.out.println("返回状态:========》"+resultDataMap.get("scode") + "==>data"+resultDataMap.get("data"));
}
public static FileItem dataFormat(File file)throws Exception{
FileItem fileItem = new DiskFileItem("mm", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());
try {
InputStream input = new FileInputStream(file);
OutputStream os = fileItem.getOutputStream();
IOUtils.copy(input, os);
//Or faster..
IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
} catch (IOException ex) {
//do something.
}
return fileItem;
}