HttpClient调用接口发送文件

客户端发送文件:

/**
	 * 文件上传
	 * @param remote_url 请求地址
	 * @param file 请求文件
	 * @return 响应结果
	 */
    public String httpClientUploadFile(String remote_url,File file) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getName();
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
       //binFile参数-服务端通过此参数获取文件 builder.addBinaryBody("binFile", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
       //filename-文件名参数 builder.addTextBody("filename", fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost);// 执行提交 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 将响应内容转换为字符串 result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }

  服务端接收文件:

@RequestMapping(value = "downloadMinimumRateFile",method = RequestMethod.POST)
public ResponseEntity<byte[]> minimumRateFileDownload(HttpServletRequest request){
  ServletContext context = request.getSession().getServletContext();
   //将当前上下文初始化给  CommonsMultipartResolver (多部分解析器)
   CommonsMultipartResolver resolver = new CommonsMultipartResolver(context);
   //判断是否多文件上传
  if (resolver.isMultipart(request)) {
        MultipartHttpServletRequest multRequest = (MultipartHttpServletRequest) request;
        MultipartFile rcvFile = multRequest.getFile("binFile");
     //具体的业务逻辑处理
     //...
     //...
  } }

 

posted @ 2020-09-03 18:06  wlv1314  阅读(1539)  评论(0编辑  收藏  举报