300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 通过HttpPost发送http请求实现文件上传

通过HttpPost发送http请求实现文件上传

时间:2021-05-29 19:09:46

相关推荐

通过HttpPost发送http请求实现文件上传

通过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;}

如还需传入其他文本参数:如下图

本人亲自验证有效。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。