本文使用的是org.apache.httpcomponents中的httpclient,因为post请求涉及到传输文件,所以需要使用httpmime这个包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
直接上代码:
package com.yappam.gmcms.utils.web.tools;
import com.google.common.collect.Maps;
import com.yappam.gmcms.utils.encrypt.HmacUtil;
import com.yappam.gmcms.utils.string.StringUtil;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.AbstractContentBody;
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;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
/**
* 类名称: HTTPUtils<br>
* 类描述: Http请求<br>
* 版权所有: Copyright (c) 2018/7/30 Zain Zhang, LTD.CO <br>
* 创建时间: 2018/7/30 14:19 <br>
*
* @author zzy <br>
* @version V1.0.0 <br>
*/
public class HttpUtils {
public static final String ENCODING = "UTF-8";
public static String get(final String url) {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
// //返回的数据包不进行压缩,解决content length为-1的问题
// httpGet.setHeader("Accept-Encoding", "identity");
System.out.println("executing get request " + httpGet.getURI());
try {
//执行get请求
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
//获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
result = EntityUtils.toString(entity, ENCODING);
// System.out.println("Response content: " + result);
}
System.out.println("------------------------------------");
} finally {
response.close();
}
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String post(final String url, Map<String, Object> params) {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
//获取请求的参数
HttpEntity requestEntity = getRequestEntity(params);
httpPost.setEntity(requestEntity);
System.out.println("executing post request " + httpPost.getURI());
//post请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
//获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
result = EntityUtils.toString(entity, ENCODING);
System.out.println("Response content: " + result);
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 通过参数获取HttpPost请求需要的参数
* 如果参数有文件,则在key之前添加file_前缀,如要传的文件key为cover,则map的key为file_cover
* @param params
* @return
*/
public static HttpEntity getRequestEntity(Map<String, Object> params) {
Map<String, AbstractContentBody> paramsPart = Maps.newHashMap();
//设置请求的参数
params.entrySet().forEach(param -> {
if (param.getKey().startsWith("file") && new File(param.getValue().toString()).isFile()) {
paramsPart.put(param.getKey().split("_")[1], new FileBody(new File(param.getValue().toString())));
}else {
paramsPart.put(param.getKey(), new StringBody(param.getValue().toString(), ContentType.create("text/plain", Consts.UTF_8)));
}
});
//拼接HttpEntity参数
MultipartEntityBuilder requestEntityBuilder = MultipartEntityBuilder.create();
paramsPart.entrySet().forEach(requestParam -> requestEntityBuilder.addPart(requestParam.getKey(), requestParam.getValue()));
return requestEntityBuilder.build();
}
}