通过HttpPost发送http请求,实现postman上传文件效果
需要引入:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.12</version>
</dependency>
** 关键代码:multipartEntityBuilder.addBinaryBody **
/**
* 发送post请求 (上传文件)
* @param url
* @param file
* @return
*/
public static String sendPost(String url, MultipartFile file) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532); // 处理中文文件名称乱码
multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
multipartEntityBuilder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getName());
multipartEntityBuilder.addTextBody("comment", file.getName());
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
如还需传入其他文本参数:如下图
文章来源:https://www.toymoban.com/news/detail-527421.html
本人亲自验证有效。文章来源地址https://www.toymoban.com/news/detail-527421.html
到了这里,关于通过HttpPost发送http请求实现文件上传的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!