/**
*
*form表单提交(带附件)
*
*
*/
public String doPost(String url, List<MultipartFile> list) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
String resultString ="";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
//传参
//流文件入参
if (!StringUtils.isEmpty(list) && !list.isEmpty()) {
for (MultipartFile s : list) {
if(!StringUtils.isEmpty(s)){
multipartEntityBuilder.addBinaryBody("files", s.getInputStream(), ContentType.create("multipart/form-data", Consts.UTF_8), s.getOriginalFilename());
}
}
}
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
// 执行http请求
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} finally {
if (response != null) {
response.close();
}
}
return resultString ;
}
Java代码中发起post请求携带文件
最新推荐文章于 2024-06-24 14:36:36 发布