0


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

通过HttpPost发送http请求,实现postman上传文件效果
postman-upload
需要引入:

<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
  */publicstaticStringsendPost(String url,MultipartFile file){// 创建Httpclient对象CloseableHttpClient httpClient =HttpClients.createDefault();CloseableHttpResponse response =null;String resultString ="";try{// 创建Http Post请求HttpPost httpPost =newHttpPost(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;}

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

本人亲自验证有效。

标签: http java postman

本文转载自: https://blog.csdn.net/qq_16771097/article/details/125084511
版权归原作者 letisgo5 所有, 如有侵权,请联系我们删除。

“通过HttpPost发送http请求实现文件上传”的评论:

还没有评论