HttpEntity multipartEntityBuilder = MultipartEntityBuilder.create().addBinaryBody("file", new File("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();
第一个参数表示请求字段名,第二个参数就是文件。
还想添加参数则
HttpEntity multipartEntityBuilder = MultipartEntityBuilder.create().addTextBody("name", "张三").addBinaryBody("file", new File("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();
httpPost.setEntity(multipartEntityBuilder);
import java.util.Map;
import org.apache.http.HttpEntity;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
public class HttpClientUtil {
private final static String CONTENT_TYPE_TEXT_JSON = "text/json";
public static String postRequest(String url, Map<String, Object> param) throws ClientProtocolException, IOException{
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
Gson gson = new Gson();
String parameter = gson.toJson(param);
StringEntity se = new StringEntity(parameter);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
httpPost.setEntity(se);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
return result;
2、返回的结果也可以使用gson转换成对象进行下一步操作。
import com.google.gson.Gson;
public class GsonUtil {
public static <T> T jsonToObject(String jsonData, Class<T> type) {
Gson gson = new Gson();
T result = gson.fromJson(jsonData, type);
return result;
public static void main(String[] args) {
String json = "{'id':'1','name':'zhang','address':'Hubei'}";
jsonToObject(json, Person.class);
Person person = jsonToObject(json, Person.class);
System.out.println(person);
建立要转成的对象的类。
import java.util.Date;
public class Person {
private int id;
private String name;
private int age;
private String address;public int getId() {
return id;
public void setId(int id) {
this.id = id;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public int getAge() {
return age;
public void setAge(int age) {
this.age = age;
public String getAddress() {
return address;
public void setAddress(String address) {
this.address = address;
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";