Apache HttpClient上传文件示例

x33g5p2x  于2022-10-07 转载在 Apache  
字(7.7k)|赞(0)|评价(0)|浏览(756)

在本文中,我们将演示如何使用Apache HttpClient 4.5+执行多部分上载操作。
我们将使用http://httpbin.org/post作为测试服务器,因为它是公共的,可以接受大多数类型的内容。
如果您想深入挖掘并学习HttpClient可以做的其他很酷的事情,请转到HttpClient主教程。

Maven依赖

我们使用maven来管理依赖项,并使用e1d1e4.5版。将以下依赖项添加到您的项目中。

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.developersguide.httpclient</groupId>
    <artifactId>apache-httpclient-guide</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <description></description>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

多部分文件上载

1.使用助手类HttpClients创建CloseableHttp客户端的实例。

CloseableHttpClient httpclient = HttpClients.createDefault()

HttpClients.createDefault()方法使用默认配置创建CloseableHttpClient实例。

2.构建多部分上传请求

// build multipart upload request
HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName())
.addTextBody("text", message, ContentType.DEFAULT_BINARY).build();

3.构建HTTP请求并分配多部分上传数据

HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName())
.addTextBody("text", message, ContentType.DEFAULT_BINARY).build();
HttpUriRequest request = RequestBuilder.post("http://httpbin.org/post").setEntity(data).build();

4.创建自定义响应处理程序

ResponseHandler<String> responseHandler = response -> {
 int status = response.getStatusLine().getStatusCode();
 if (status >= 200 && status < 300) {
  HttpEntity entity = response.getEntity();
  return entity != null ? EntityUtils.toString(entity) : null;
 } else {
  throw new ClientProtocolException("Unexpected response status: " + status);
 }
};

创建多部分实体的更直接方法是使用addBinaryBodyAddTextBody方法。这些方法用于上载文本、文件、字符数组和InputStream对象。
让我们使用MultipartEntityBuilder创建一个HttpEntity。当我们创建构建器时,我们添加了一个二进制体——包含将要上载的文件和一个文本体。

package com.javadevelopersguide.httpclient.examples;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
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;

/**
* This example demonstrates the use of {@link HttpPost} request method.
* And sending Multipart Form requests
* @author Ramesh Fadatare
*/
public class HttpClientMultipartUploadExample {
    public static void main(String...args) throws IOException {

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            File file = new File("demo.png");
            String message = "This is a multipart post";

            // build multipart upload request
            HttpEntity data = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName())
                .addTextBody("text", message, ContentType.DEFAULT_BINARY).build();

            // build http request and assign multipart upload data
            HttpUriRequest request = RequestBuilder.post("http://httpbin.org/post").setEntity(data).build();

            System.out.println("Executing request " + request.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(request, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

输出

Executing request POST http://httpbin.org/post HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "data": "", 
  "files": {
    "upfile": "data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUgAAA0YAAADmCAYAAADx0JVrAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJ..."
  }, 
  "form": {
    "text": "This is a multipart post"
  }, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "9527", 
    "Content-Type": "multipart/form-data; boundary=IJeEBy_OHEtuA2sJyD2wp9S7YXhruSRMLYg4Z", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
  }, 
  "json": null, 
  "origin": "49.35.12.218", 
  "url": "http://httpbin.org/post"
}

使用AddPart方法

让我们从查看MultipartEntityBuilder对象开始,将部件添加到Http实体,然后通过POST操作上传该实体。
这是一种向表示表单的HttpEntity中添加部件的通用方法。让我们看看示例代码示例:

package com.javadevelopersguide.httpclient.siteexamples;

import java.io.File;

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.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                "/servlets-examples/servlet/RequestInfoExample");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

查看https://www.baeldung.com/httpclient-multipart-upload文章,了解更多上传字节数组、文本、Zip文件、图像文件和文本部分的信息。

相关文章