HttpClient 发送接口传文件

该博客介绍了如何使用Apache HttpClient库在Java中实现文件的上传和下载操作。在发送端,通过创建HttpPost实例,设置文件作为POST请求的实体,并利用MultipartEntityBuilder将文件内容转换为HTTP请求的一部分。在接收端,通过HttpServletRequest获取上传的文件并保存到服务器。整个过程涉及到HTTP客户端库的使用、文件流处理以及MultipartFile的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

发送端
1.引入依赖

     <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
      </dependency>
      <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.3</version>
      </dependency>

2.发送端

      //需要传入的文件
        File file = new File("D:/copyright.jsp");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //url 调用接口传递文件
        HttpPost httpPost = new HttpPost("http://" +url);
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        fileInputStream.read(buffer);
        fileInputStream.close();
        InputStream inputStream = new ByteArrayInputStream(buffer);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        // 把文件加到HTTP的post请求中
        builder.addBinaryBody("files", inputStream, ContentType.MULTIPART_FORM_DATA, file.getName());
        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String  responseJsonString = EntityUtils.toString(responseEntity, "UTF-8");
        log.info("调用上传文件接口返回结果===>>" + responseJsonString);
        inputStream.close();

3.接收端

  public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("files");// 获取上传文件对象
    File savefile = new File("D://copyrightCopy.jsp");
    FileCopyUtils.copy(file.getBytes(), savefile);
  
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值