通过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;}
如还需传入其他文本参数:如下图
本人亲自验证有效。