在本文中,我们将演示如何使用Apache HttpClient 4.5+执行多部分上载操作。
我们将使用http://httpbin.org/post作为测试服务器,因为它是公共的,可以接受大多数类型的内容。
如果您想深入挖掘并学习HttpClient
可以做的其他很酷的事情,请转到HttpClient主教程。
我们使用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>
CloseableHttpClient httpclient = HttpClients.createDefault()
HttpClients.createDefault()
方法使用默认配置创建CloseableHttpClient
实例。
// 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();
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();
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);
}
};
创建多部分实体的更直接方法是使用addBinaryBody
和AddTextBody
方法。这些方法用于上载文本、文件、字符数组和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"
}
让我们从查看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文件、图像文件和文本部分的信息。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/10/apache-httpclient-upload-file-example.html
内容来源于网络,如有侵权,请联系作者删除!