HttpClient 发送文件流

使用Maven与HttpClient上传文件
本文介绍如何利用Maven依赖的Apache HttpClient组件,通过Java代码实现文件的HTTP POST上传,包括设置请求头、构建MultipartEntity,以及服务器端如何接收和处理上传的文件。
  • Maven依赖
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.8</version>
        </dependency>
  • HttpPost 发送文件流
public void upload(String localFile, String filename){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();

            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost("http://127.0.0.1:8081/chapter01/upload/processUpload");

            // 把文件转换成流对象FileBody
            //FileBody bin = new FileBody(new File(localFile));
            InputStreamBody bin = new InputStreamBody(new FileInputStream(localFile), filename);

            StringBody userName = new StringBody("Scott", ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody password = new StringBody("123456", ContentType.create(
                    "text/plain", Consts.UTF_8));
            StringBody filenamebody = new StringBody(filename, ContentType.create(
                    "text/plain", Consts.UTF_8));

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .setCharset(Charset.forName("UTF-8"))
                    // 相当于<input type="file" name="file"/>
                    .addPart("file", bin)
                    // 相当于<input type="text" name="userName" value=userName>
                    .addPart("userName", userName)
                    .addPart("pass", password)
                    .addPart("filenamebody",filenamebody)
                    .build();

            httpPost.setEntity(reqEntity);

            // 发起请求 并返回请求的响应
            response = httpClient.execute(httpPost);

            System.out.println("The response value of token:" + response.getFirstHeader("token"));

            // 获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // 打印响应长度
                System.out.println("Response content length: " + resEntity.getContentLength());
                // 打印响应内容
                System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
            }
            // 销毁
            EntityUtils.consume(resEntity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 服务器端接收文件流
@RequestMapping("/processUpload")
    public void processUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("filenamebody") String filenamebody, @RequestParam("file") MultipartFile file) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            String name1 = file.getName();
            byte[] bytes = file.getBytes();
            //FileUtils.writeByteArrayToFile(new File("C:\\Users\\wangdongjiang\\Desktop\\wdj\\" + name1), bytes);
            response.addHeader("token", "hello");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

### HttpClientUtils 文件流处理示例 当使用 `HttpClient` 进行文件上传或下载操作时,通常会涉及到文件流的处理。下面展示了一个基于 Apache HttpClient 的实用工具类 (`HttpClientUtils`) 来实现文件流的操作。 #### 文件上传示例 为了发送带有附件的数据到服务器端,在构建请求体的时候需要用到 `MultipartEntityBuilder` 类来组装表单字段以及二进制数据: ```java import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpClientUtils { public static void uploadFile(String url, File file) throws Exception { CloseableHttpClient client = HttpClients.createDefault(); try { HttpPost post = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody( "file", // 表单项名称 file, ContentType.APPLICATION_OCTET_STREAM, // MIME类型 file.getName()); // 可选参数 post.setEntity(builder.build()); try (CloseableHttpResponse response = client.execute(post)) { System.out.println(response.getStatusLine().getStatusCode()); } } finally { client.close(); } } } ``` 此代码片段展示了如何创建一个多部分实体并将其附加至 HTTP POST 请求中[^3]。 #### 文件下载示例 对于从远程位置获取资源的情况,则可以通过读取响应中的输入流并将内容写入本地磁盘完成下载过程: ```java import java.io.FileOutputStream; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; // ... 继续上面定义的 HttpClientUtils 类 public static void downloadFile(String url, Path destinationPath) throws IOException { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet get = new HttpGet(url); HttpResponse httpResponse = client.execute(get); InputStream inputStream = httpResponse.getEntity().getContent(); Files.copy(inputStream, destinationPath); int statusCode = httpResponse.getStatusLine().getStatusCode(); if(statusCode != 200){ throw new RuntimeException("Failed to download file with status code:" + statusCode); } System.out.println("Download completed successfully."); } } ``` 上述例子说明了怎样利用 Java NIO API 将来自网络连接的数据保存成物理文件。 通过这些方法,可以方便地集成文件传输功能于应用程序之中,无论是上载还是下拉都变得简单明了。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值