注意:在HttpClient4.3之后,原来的上传文件方法MultipartEntity已经不建议使用,现替换成新的httpmime下面的MultipartEntityBuilder。
需要添加httpclient-4.5.jar、httpmime-4.5.jar两个包
maven添加:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
下面我们对比一下MultipartEntity和MultipartEntityBuilder的使用区别:
MultipartEntityBuilder:
//传入参数可以为file或者filePath,在此处做转换
File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//设置浏览器兼容模式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//设置请求的编码格式
builder.setCharset(Consts.UTF_8);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
//添加文件
builder.addBinaryBody("file", file);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
httpResponse = httpClient.execute(httppost);
MultipartEntity:
//传入参数可以为file或者filePath,在此处做转换
File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
HttpPost httppost = new HttpPost(url);
FileBody filebody = new FileBody(file);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
Charset.forName("UTF-8"));
entity.addPart("file", filebody);
httppost.setEntity(entity);
直接替换后的测试代码
package com.test.util;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
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.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;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
public class HttpPostUploadUtil {
/**
* @param args
*/
public static void main(String[] args) {
String filePath = "D:\\Test\\0.jpg";
String url = "http://127.0.0.1:8080/FastFds";
//调用上传方法
String backInfo = uploadPost(url, filePath);
if(StringUtils.isNotBlank(backInfo)){
//转json数据
JSONObject json = JSONObject.fromObject(backInfo);
if(!json.isEmpty()){
//数据处理
String value = json.getString("test");
System.out.println(value);
}
}
}
/**
* 上传图片/文件
* @param url
* @param filePath
* @return String 用于转json或者其他信息
*/
public static String uploadPost(String url, String filePath) {
String requestJson = "";
//传入参数可以为file或者filePath,在此处做转换
File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//设置浏览器兼容模式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//设置请求的编码格式
builder.setCharset(Consts.UTF_8);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
//添加文件
builder.addBinaryBody("file", file);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
httpResponse = httpClient.execute(httppost);
int backCode = httpResponse.getStatusLine().getStatusCode();
if(backCode == HttpStatus.SC_OK){
HttpEntity httpEntity = httpResponse.getEntity();
byte[] json= EntityUtils.toByteArray(httpEntity);
requestJson = new String(json, "UTF-8");
//关闭流
EntityUtils.consume(httpEntity);
return requestJson;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//释放资源
try {
httpClient.close();
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
主要方法说明:
addBinaryBody、addPart、addTextBody方法用于添加要上传的数据,从上面的表格中可以发现用于添加数据的方法,都是key-value类型。所以在服务器端我们可以通过request.getPart(“keyname”)方式获取对应key的数据。也可以通过request.getParts()方式获取客户端通过以上三种方法提交所有数据。
1.通过addBinaryBody方法直接可以添加File、InputStream、byte[]类型的数据。
2.通过addPart方法只能添加ContentBody类型的数据,在org.apache.http.entity.mime.content包中已经提供了String、File以及InputStream对应的ContentBody类型的子类,如FileBody、InputStreamBody、StringBody,通过这些类我们可以将String、File以及InputStream类型的数据转换成ContentBody类型的数据。
3.通过addTextBody方法我们可以很方便的添加文本数据。