HttpClientUtil 包含get和post方法。
发送HttpPost或HttpGet请求一共三个步骤:
1、创建CloseableHttpClient对象,用于执行excute方法
2、创建HttpPost或者HttpGet请求对象
3、执行请求,判断返回状态,接收响应对象
public class HttpClientUtil {
/***
* 编码集
*/
private final static String CHAR_SET = "UTF-8";
/***
* Post表单请求形式请求头
*/
private final static String CONTENT_TYPE_POST_FORM = "application/x-www-form-urlencoded";
/***
* Post Json请求头
*/
private final static String CONTENT_TYPE_JSON = "application/json";
/***
* 连接管理器
*/
private static PoolingHttpClientConnectionManager poolManager;
/***
* 请求配置
*/
private static RequestConfig requestConfig;
static {
// 静态代码块,初始化HtppClinet连接池配置信息,同时支持http和https
try {
System.out.println("初始化连接池-------->>>>开始");
// 使用SSL连接Https
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLContext sslContext = builder.build();
// 创建SSL连接工厂
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build();
// 初始化连接管理器
poolManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 设置最大连接数
poolManager.setMaxTotal(1000);
// 设置最大路由
poolManager.setDefaultMaxPerRoute(300);
// 从连接池获取连接超时时间
int coonectionRequestTimeOut = 5000;
// 客户端和服务器建立连接超时时间
int connectTimeout = 5000;
// 客户端从服务器建立连接超时时间
int socketTimeout = 5000;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(coonectionRequestTimeOut)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout).build();
System.out.println("初始化连接池-------->>>>结束");
} catch (Exception e) {
e.printStackTrace();
System.out.println("初始化连接池-------->>>>失败");
}
}
public static String doGet(String url, Map<String, String> params) {
String result = "";
// 获取http客户端
// CloseableHttpClient httpClient = getCloseableHttpClient();
// 获取http客户端从连接池中
CloseableHttpClient httpClient = getCloseableHttpClientFromPool();
// 响应模型
CloseableHttpResponse httpResponse = null;
try {
// 创建URI 拼接请求参数
URIBuilder uriBuilder = new URIBuilder(url);
// uri拼接参数
if (null != params) {
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> next = it.next();
uriBuilder.addParameter(next.getKey(), next.getValue());
}
}
URI uri = uriBuilder.build();
// 创建Get请求
HttpGet httpGet = new HttpGet(uri);
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 获取响应实体
HttpEntity httpEntity = httpResponse.getEntity();
if (null != httpEntity) {
result = EntityUtils.toString(httpEntity, CHAR_SET);
System.out.println("响应内容:" + result);
return result;
}
}
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println("响应码:" + statusCode);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != httpResponse) {
httpResponse.close();
}
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
private static CloseableHttpClient getCloseableHttpClient() {
return HttpClientBuilder.create().build();
}
/**
* 从http连接池中获取连接
*/
private static CloseableHttpClient getCloseableHttpClientFromPool() {
//
ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new ServiceUnavailableRetryStrategy() {
@Override
public boolean retryRequest(HttpResponse httpResponse, int executionCount, HttpContext httpContext) {
if (executionCount < 3) {
System.out.println("ServiceUnavailableRetryStrategy");
return true;
} else {
return false;
}
}
// 重试时间间隔
@Override
public long getRetryInterval() {
return 3000L;
}
};
// 设置连接池管理
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolManager)
// 设置请求配置策略
.setDefaultRequestConfig(requestConfig)
// 设置重试次数
.setRetryHandler(new DefaultHttpRequestRetryHandler()).build();
return httpClient;
}
/**
* Post请求,表单形式
*/
public static String doPost(String url, Map<String, String> params) {
String result = "";
// 获取http客户端
CloseableHttpClient httpClient = getCloseableHttpClient();
// 响应模型
CloseableHttpResponse httpResponse = null;
try {
// Post提交封装参数列表
ArrayList<NameValuePair> postParamsList = new ArrayList<>();
if (null != params) {
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> next = it.next();
postParamsList.add(new BasicNameValuePair(next.getKey(), next.getValue()));
}
}
// 创建Uri
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(postParamsList, CHAR_SET);
// 设置表达请求类型
urlEncodedFormEntity.setContentType(CONTENT_TYPE_POST_FORM);
HttpPost httpPost = new HttpPost(url);
// 设置请求体
httpPost.setEntity(urlEncodedFormEntity);
// 执行post请求
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity(), CHAR_SET);
//System.out.println("Post form reponse {}" + result);
return result;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
CloseResource(httpClient, httpResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
private static void CloseResource(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) throws IOException {
if (null != httpResponse) {
httpResponse.close();
}
if (null != httpClient) {
httpClient.close();
}
}
/***
* Post请求,Json形式
*/
public static String doPostJson(String url, String jsonStr) {
String result = "";
CloseableHttpClient httpClient = getCloseableHttpClient();
CloseableHttpResponse httpResponse = null;
try {
// 创建Post
HttpPost httpPost = new HttpPost(url);
// 封装请求参数
StringEntity stringEntity = new StringEntity(jsonStr, CHAR_SET);
// 设置请求参数封装形式
stringEntity.setContentType(CONTENT_TYPE_JSON);
httpPost.setEntity(stringEntity);
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(httpResponse.getEntity(), CHAR_SET);
System.out.println(result);
return result;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
CloseResource(httpClient, httpResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
// get 请求
//String getUrl = "https://www.baidu.com/s";
//String getUrl = "http://localhost:9888/boxes/getprojectdaystats";
//String getUrl = "https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json";
//Map m = new HashMap();
// m.put("year","2023");
// m.put("age","123");
//String result = doGet(getUrl,m );
// System.out.println("result = " + result);
//Post 请求 baocuo
// String postUrl = "http://localhost:8088/device/factmag/getInfo";
// Map m = new HashMap();
//m.put("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjNkNmI3ZTFjLTU0ZjgtNGE2NS1iMTY1LTE2NjczYzM1MWIxZiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.AyLfDdY9PjpWInEnaiDUBdJVpStEsP1oheWrxCdRcflzJSWPL2VMFFL2SngTO5S0jrI3uwQBWAsccCOG4hRygg");
//m.put("facregCode","999999");
// String s = doPost(postUrl, m);
//System.out.println("s = " + s);
//String postJsonUrl = "http://127.0.0.1:8080/testHttpClientUtilPostJson";
/* User user = new User();
user.setUid("123");
user.setUserName("小明");
user.setAge("18");
user.setSex("男");
String jsonStr = JSON.toJSONString(user);
doPostJson(postJsonUrl,jsonStr); */
// System.out.println(s);
// System.out.println(result);
}
}
![](/i/l/?n=23&i=blog/3073776/202306/3073776-20230604184431896-389541070.gif)
![点击并拖拽以移动](/i/l/?n=23&i=blog/3073776/202306/3073776-20230604184431896-389541070.gif)