写了一个 HttpUtil 工具类,精简版的,没有具体测试,有兴趣可以自行完善。
代码说明:
- HttpClients.createDefault() 获取到的是类 CloseableHttpClient 的子类 InternalHttpClient 的实例,它是线程安全的,因为在类上面标注了,且不能被继承。
- 使用 CloseableHttpClient 发送请求,会自动调用 PoolingHttpClientConnectionManager 来管理连接,请求完成后,会释放连接,但不会关闭连接。
- 使用 ResponseHandler 可以简化代码,不用手动去解析请求返回结果 HttpResponse 以及 HttpEntity,也不用手动关闭 HttpEntity 的文本流,ResponseHandler 都帮我们做了,它的实现类 BasicResponseHandler 也是线程安全的。
package com.example.springboot01.util;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtil {
public static final CloseableHttpClient httpClient = HttpClients.createDefault();
public static final ResponseHandler<String> responseHandler = new BasicResponseHandler();
/**
* get请求
* @param url 请求地址
* @return 返回结果
* @throws IOException 请求异常
*/
public static String doGet(String url) throws IOException {
HttpGet httpGet = new HttpGet(url);
return httpClient.execute(httpGet, responseHandler);
}
/**
* post请求
* @param url 请求地址
* @param paramMap 请求参数
* @return 返回结果
* @throws IOException 请求异常
*/
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> pairList = setHttpParams(paramMap);
httpPost.setEntity(new UrlEncodedFormEntity(pairList, "UTF-8"));
return httpClient.execute(httpPost, responseHandler);
}
/**
* put请求
* @param url 请求地址
* @param params 请求参数
* @return 返回结果
* @throws IOException 请求异常
*/
public static String doPut(String url, Map<String, String> params) throws IOException {
HttpPut httpPut = new HttpPut(url);
List<NameValuePair> pairList = setHttpParams(params);
httpPut.setEntity(new UrlEncodedFormEntity(pairList, "UTF-8"));
return httpClient.execute(httpPut, responseHandler);
}
/**
* delete请求
* @param url 请求地址
* @return 返回结果
* @throws IOException 请求异常
*/
public static String doDelete(String url) throws IOException {
HttpDelete httpDelete = new HttpDelete(url);
return httpClient.execute(httpDelete, responseHandler);
}
/**
* 设置请求参数
*/
private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
List<NameValuePair> pairList = new ArrayList<>();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return pairList;
}
}