一、MultipartEntityBuilder的概述
MultipartEntityBuilder是Apache HttpClient库中的一个类,提供了便捷的构建multipart请求的能力。一般地,我们使用multipart请求是需要上传文件或者提交多个参数。如果使用普通请求,一般是无法处理这些情况的。 相对于上一个版本的HttpMultipart,MultipartEntityBuilder改进了参数的添加方法,并提供了更加丰富的定制化能力。
二、MultipartEntityBuilder的使用
MultipartEntityBuilder提供了多种添加参数的方法,本节中我们将会一一阐述:
1.添加文本参数
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", "admin");
builder.addTextBody("password", "123456");
httpPost.setEntity(builder.build());
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
addTextBody()
方法的前两个参数分别为参数名和参数值。当然,也可以使用addParameter
方法添加,效果是一样的。
2.添加二进制文件
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File file = new File("/path/to/file");
builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, "filename");
httpPost.setEntity(builder.build());
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
addBinaryBody()
方法的前三个参数分别为参数名、文件和Content-Type。
3.添加纯文本文件
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String text = "this is a plain text";
builder.addTextBody("text", text, ContentType.DEFAULT_TEXT);
httpPost.setEntity(builder.build());
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
4.定制化MultipartEntity
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setCharset(StandardCharsets.UTF_8);
builder.addPart("file", new ByteArrayBody(fileContent, "filename"));
builder.addPart("text", new StringBody("this is a plain text", ContentType.DEFAULT_TEXT));
builder.addPart("parameter", new StringBody("parameter-value", ContentType.DEFAULT_BINARY));
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
setMode
方法设置Multipart模式,对应不同的RFC规范;setCharset
方法设置编码;addPart
方法提供了更加灵活的添加参数方法。
三、MultipartEntityBuilder的附加功能
1.追加参数
在上一个例子中,如果你想要在上传文件的同时上传其他参数,可以使用addPart
方法,但是如果你希望追加参数,可以使用addTextBody
/addBinaryBody
方法,如下:
builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, "filename");
builder.addTextBody("username", "admin");
builder.addTextBody("password", "123456");
2.文件流转换
在某些情况下,我们需要将文件转换成其他格式,比如Base64。此时,MultipartEntityBuilder提供了stream方式的addBinaryBody
方法,如下:
builder.addBinaryBody("file", new ByteArrayInputStream(Base64.encode(fileContent.getBytes())), ContentType.DEFAULT_BINARY, "filename");
3.支持参数排序
在某些场景下,需要按照参数名称做排序,MultipartEntityBuilder提供了Comparator接口,你可以自定义该接口来实现参数排序,如下:
builder.setSortOrder(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
四、总结
本文通过具体的例子介绍了MultipartEntityBuilder的使用,包括文本参数、二进制文件、纯文本文件、定制化MultipartEntity、追加参数、文件流转换以及参数排序等相关功能。这些都为我们优美地处理多样化的请求提供了强有力的工具。