使用HttpClient发送InputStream对象及发送文件

最近在做的东西中有这样一个需求要把一个文件上传到服务器A上,再由服务器A上传到服务器B上,而服务器A上传到服务器B的这个请求是通过HttpClient发送的。如果是发送文件的话很好办,但是现在问题的难点是服务器A通过HttpClient发送的不是一个文件,而是一个InputStream对象。一个折中的办法是先把文件临时存储在服务器A上,然后再从服务器A上读取文件发送到服务器B上,那么有没有办法直接发送InputStream对象呢?答案是肯定的,我在这里找到了答案:http://www.baeldung.com/httpclient-multipart-upload

接着自己写了一个例子测试了一下果断拿来用了。现在把这个小例子写一下,希望能帮到遇到同样问题的同学。

准备工作

我们需要引入这两个Maven依赖:
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
				<version>4.3.6</version>
			</dependency>
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpmime</artifactId>
				<version>4.3.6</version>
			</dependency>
另外我们还需要写一个接收文件上传的处理类。这里我们用上一篇文章中写好的。链接在这里: http://blog.csdn.net/zknxx/article/details/72633444

HttpClient发送InputStream对象

接着进入我们的正题,使用HttpClient发送InputStream对象,程序如下:
    @Test
    public void inputStreamUpload() {
        //创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //构建POST请求   请求地址请更换为自己的。
        //1)
        HttpPost post = new HttpPost("http://localhost:8003/uploadAndDownload/uploadFileAction");
        InputStream inputStream = null;
        try {
            //文件路径请换成自己的
            //2)
            inputStream = new FileInputStream("G:\\LearnVideo\\text01.txt");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
            //第三个参数是文件名
            //3)
            builder.addBinaryBody("uploadFile", inputStream, ContentType.create("multipart/form-data"), "text01.txt");
            //4)构建请求参数 普通表单项
            StringBody stringBody = new StringBody("12",ContentType.MULTIPART_FORM_DATA);
            builder.addPart("id",stringBody);
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            //发送请求
            HttpResponse response = client.execute(post);
            entity = response.getEntity();
            if (entity != null) {
                inputStream = entity.getContent();
                //转换为字节输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8));
                String body = null;
                while ((body = br.readLine()) != null) {
                    System.out.println(body);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
请注意上面程序中的1)、2)、3)、4)处。下面再写一个用HttpClient发送文件的小例子:

HttpClient发送文件

   @Test
    public  void fileUpload() {
        //构建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //构建POST请求
        HttpPost httpPost = new HttpPost("http://localhost:8003/uploadAndDownload/uploadFileAction");
        InputStream inputStream = null;
        try {
            //要上传的文件
            File file = null; file = new File("G:\\qqq.txt");
            //构建文件体
            FileBody fileBody = new FileBody(file,ContentType.MULTIPART_FORM_DATA,"qqq.txt");
            StringBody stringBody = new StringBody("12",ContentType.MULTIPART_FORM_DATA);
            HttpEntity httpEntity = MultipartEntityBuilder
                    .create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("uploadFile", fileBody)
                    .addPart("id",stringBody).build();
            httpPost.setEntity(httpEntity);
            //发送请求
            HttpResponse response = client.execute(httpPost);
            httpEntity = response.getEntity();
            if(httpEntity != null){
                inputStream = httpEntity.getContent();
                //转换为字节输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8));
                String body = null;
                while ((body = br.readLine()) != null) {
                    System.out.println(body);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

希望能帮助到需要的朋友。
使用Apache HttpClient发送文件可以使用MultipartEntityBuilder。这个类可以将多个part组合成multipart/form-data格式的请求实体。 下面是一个发送文件的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.http.HttpEntity; 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; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://your-url.com/upload"); File file = new File("path/to/your/file"); InputStream inputStream = new FileInputStream(file); HttpEntity httpEntity = MultipartEntityBuilder.create() .addBinaryBody("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, file.getName()) .addTextBody("description", "This is a large file upload test", ContentType.create("text/plain", StandardCharsets.UTF_8)) .build(); httpPost.setEntity(httpEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity responseEntity = response.getEntity(); System.out.println(EntityUtils.toString(responseEntity)); } finally { response.close(); } } } ``` 在此代码中,我们首先创建了一个CloseableHttpClient对象,然后创建一个HttpPost对象并设置目标URL。接下来,我们打开文件并将其添加到multipart实体中。最后,我们执行HTTP POST请求并关闭响应。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值