HttpClient 调用接口类

package com.hnbits.bys.util;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class HttpClientUtil {

private static CloseableHttpClient httpClient;

private static RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(25000)
.setConnectTimeout(25000)
.setConnectionRequestTimeout(25000)
.build();

static {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(300);
connManager.setDefaultMaxPerRoute(300);
httpClient = HttpClients.custom().setConnectionManager(connManager).build();
}

// get请求
public static JSONObject get(String url,Map<String, String> params) throws IOException, URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(url);
if(null != params) {
for (Entry<String, String> entry : params.entrySet()) {
uriBuilder.setParameter(entry.getKey(),entry.getValue());
}
}
HttpGet httpget = new HttpGet(uriBuilder.build());
httpget.setConfig(requestConfig);
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
//输出调用结果
if(response != null && response.getStatusLine().getStatusCode() == 200) {
// 生成 JSON 对象
JSONObject obj = JSONObject.parseObject(result);
return obj;
}
return null;
}
}

// post请求
public static JSONObject post(String url, JSONObject params) throws IOException {
HttpPost httpPost = new HttpPost(url);
if(null != params) {
HttpEntity entity = new StringEntity(params.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
}
httpPost.setConfig(requestConfig);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
//输出调用结果
if(response != null && response.getStatusLine().getStatusCode() == 200) {
// 生成 JSON 对象
JSONObject obj = JSONObject.parseObject(result);
return obj;
}
return null;
}
}

}

posted @ 2021-09-10 17:38  看看反馈  阅读(77)  评论(0)    收藏  举报