上一篇文章中,通过HttpClient实现了简单的get请求并处理服务器返回的资源,在很多的场景中,我们也需要向服务器上传我们的信息。
以下分析使用版本为:
httpclient-4.5.3.jar
httpcore-4.4.6.jar
httpmime-4.5.3.jar
jdk1.8.0_131
所有示例代码均经过运行测试
表单提交
调用第三方接口或者模拟表单提交的时候,常常会使用到post请求,与get请求不同的是,post请求的参数并不是通过URL来进行传递,而是封装在请求报文的正文中。HttpClient提供了UrlEncodedFormEntity类来处理此类场景。生成UrlEncodedFormEntity实例时需指定编码为UTF-8,否则中文到了服务端会乱码。
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
try {
httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/Crayfish/HttpClientServer");
HttpEntity formEntity = getFormEntity();
post.setEntity(formEntity);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
CommonUtils.closeResponse(response);
CommonUtils.closeHttpClient(httpclient);
}
public HttpEntity getFormEntity() throws UnsupportedEncodingException {
List formParams = new ArrayList<>();
formParams.add(new BasicNameValuePair("name", "果林椰子"));
formParams.add(new BasicNameValuePair("password", "helloWord!"));
return new UrlEncodedFormEntity(formParams, "UTF-8");
}
模拟服务端
为了便于测试请求效果,基于Tomcat+servlet本地搭建了一个服务端,并将接收到的请求参数直接打印到控制台,服务端相关代码如下。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map paramMap = request.getParameterMap();
for (Entry paramEntry : paramMap.entrySet()) {
String val = paramEntry.getValue()[0];
String info = String.format("key:%s, val:%s.", paramEntry.getKey(), val);
System.out.println(info);
}
response.getWriter().append("Success!");
}
服务端输出
key:name, val:果林椰子.
key:password, val:helloWord!.
文件上传
表单提交时,参数被封装进UrlEncodedFormEntity这个类中。相似地,文件上传时,文件信息被封装到MultipartFormEntity这个类中,这两个类均实现了HttpEntity接口。
为了方便实现文件上传,HttpClients提供了MultipartEntityBuilder这个工具类来生成MultipartFormEntity,MultipartEntityBuilder支持三种方式来添加文件信息,分别是File文件,byte数组,InputStream文件流。
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
try {
httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/Crayfish/FileUpload");
HttpEntity dataEntity = getMultiFileEntity();//File文件格式上传
// HttpEntity dataEntity = getMultiDefaultFileEntity();//File文件格式上传(缺省)
// HttpEntity dataEntity = getMultiArrayEntity();//byte数组格式上传
// HttpEntity dataEntity = getMultiDefaultArrayEntity();//byte数组格式上传(缺省)
// HttpEntity dataEntity = getMultiStreamEntity();//文件流格式上传
// HttpEntity dataEntity = getMultiDefaultStreamEntity();//文件流格式上传(缺省)
post.setEntity(dataEntity);
response = httpclient.execute(post);
} catch (Exception e) {
e.printStackTrace();
} finally {
CommonUtils.closeResponse(response);
CommonUtils.closeHttpClient(httpclient);
}
/**
* File文件格式上传
*/
public HttpEntity getMultiFileEntity() {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File file = new File("F:/PIC/house.jpeg");;
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, "photo.jpg");
return builder.build();
}
/**
* File文件格式上传(缺省)
*/
public HttpEntity getMultiDefaultFileEntity() {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File file = new File("F:/PIC/house.jpeg");
builder.addBinaryBody("file", file);
return builder.build();
}
/**
* byte数组格式上传
*/
public HttpEntity getMultiArrayEntity() {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
byte[] byteArr = getFileArr();
builder.addBinaryBody("file", byteArr, ContentType.DEFAULT_BINARY, "photoArr.jpg");
return builder.build();
}
/**
* byte数组格式上传(缺省)
*/
public HttpEntity getMultiDefaultArrayEntity() {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
byte[] byteArr = getFileArr();
builder.addBinaryBody("file", byteArr);
return builder.build();
}
public byte[] getFileArr() {
try {
File file = new File("F:/PIC/house.jpeg");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
return bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return new byte[0];
}
}
/**
* 文件流格式上传
*/
public HttpEntity getMultiStreamEntity() throws FileNotFoundException {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File file = new File("F:/PIC/house.jpeg");
InputStream stream = new FileInputStream(file);
builder.addBinaryBody("file", stream, ContentType.DEFAULT_BINARY, "photoStream.jpg");
return builder.build();
}
/**
* 文件流格式上传(缺省)
*/
public HttpEntity getMultiDefaultStreamEntity() throws FileNotFoundException {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File file = new File("F:/PIC/house.jpeg");
InputStream stream = new FileInputStream(file);
builder.addBinaryBody("file", stream);
return builder.build();
}
File文件格式上传
getMultiFileEntity中调用了MultipartEntityBuilder中的addBinaryBody方法,第一个参数"file"代表字段名,相当于,第二个参数是读取的文件类,第三个参数ContentType.DEFAULT_BINARY指定了发送http请求时的content-type为application/octet-stream,第四个参数代表文件名。
也可采用缺省方式getMultiDefaultFileEntity,查看源码可以发现,content-type默认为ContentType.DEFAULT_BINARY,文件名会取文件本来的名字
public MultipartEntityBuilder addBinaryBody(final String name, final File file) {
return addBinaryBody(name, file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
}
byte数组格式上传
getMultiArrayEntity中调用addBinaryBody时,传入的是一个byte数组,其他参数与第一种方式相同。
byte数组方式上传,同样提供了默认方式(参见getMultiDefaultArrayEntity),但是若采用默认方式,上传到服务器后,文件名为null且没有后缀,会影响文件正常显示。
文件流格式上传
getMultiStreamEntity中调用addBinaryBody时,传入的是一个InputStream,其他参数与第一种方式相同。
文件流方式上传,也提供了默认方式(参见getMultiDefaultStreamEntity),但是若采用默认方式,上传到服务器后,文件名也会为null且没有后缀,会影响文件正常显示。
服务端接收代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List formItems = fileUpload.parseRequest(request);
for (FileItem item : formItems) {
String filename = item.getName();
File newFile = new File("F:/eclipseOutput/PIC/"+filename);
item.write(newFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
附录 CommonUtils
public void closeResponse(CloseableHttpResponse response) {
try {
if (response != null) {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeHttpClient(CloseableHttpClient httpclient) {
try {
if (httpclient != null) {
httpclient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}