Http请求工具类
一、使用现成的工具类:HuTool
链接:Hutool官网
依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.22</version>
</dependency>
二、使用自己封装的工具类
依赖:
<!-- gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6</version>
</dependency>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
代码:
public class HttpUtils {
/**
* 带参数的get请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public static String doGet(String url, Map<String, Object> map)
throws Exception {
// 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url);
// 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
// 设置参数
uriBuilder.setParameter(entry.getKey(), entry.getValue()
.toString());
}
}
// 2 创建httpGet对象,相当于设置url请求地址
HttpGet httpGet = new HttpGet(uriBuilder.build());
return sendHttpReq(httpGet);
}
/**
* 不带参数的get请求
*
* @param url
* @return
* @throws Exception
*/
public static String doGet(String url) throws Exception {
return doGet(url,null);
}
/**
* 带参数的post请求
*
* @param url
* @return
* @throws Exception
*/
public static String doPost(String url, Map<String, Object> reqMap,
Map<String, String> headersMap) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, String> entry : headersMap.entrySet())
httpPost.addHeader(entry.getKey(), entry.getValue());
// 判断map不为空
if (reqMap != null) {
Gson gson = new GsonBuilder().create();
// 创建form表单对象
StringEntity formEntity = new StringEntity(gson.toJson(reqMap),
"UTF-8");
// 把表单对象设置到httpPost中
httpPost.setEntity(formEntity);
}
return sendHttpReq(httpPost);
}
private static String sendHttpReq(HttpUriRequest method) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(method);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception var14) {
throw new RuntimeException(var14);
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException var13) {
var13.printStackTrace();
}
}
return responseContent;
}
}