HttpClient工具类
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.routing.HttpRoute;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.pool.PoolStats;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class HttpClient {
static final int TIMEOUT_MSEC = 5 * 1000;
private static Logger logger = LoggerFactory.getLogger(HttpClient.class);
private static final String DEFAULT_CHARSET = "UTF-8";
private static final Byte[] LOCKS = new Byte[0];
private volatile static HttpClient INSTANCE = null;
private DefaultHttpClientConfig httpClientConfig = null;
private CloseableHttpClient httpClient;
private PoolingHttpClientConnectionManager connectionManager;
private Lock lock = new ReentrantLock();
private static ConcurrentHashMap<Integer, RequestConfig> requstConfigCache = new ConcurrentHashMap<Integer, RequestConfig>(10);
private HttpClient(DefaultHttpClientConfig httpClientConfig) {
this.httpClientConfig =httpClientConfig;
}
public static HttpClient getHttpClient(DefaultHttpClientConfig httpClientConfig) {
if(INSTANCE==null){
synchronized (LOCKS) {
if(INSTANCE==null){
if(httpClientConfig==null){
httpClientConfig=new DefaultHttpClientConfig();
}
INSTANCE = new HttpClient(httpClientConfig);
}
}
}
return INSTANCE;
}
public RequestConfig getRequestConfig(int timeout)
{
if(timeout==0)
{
timeout = 3000;
}
RequestConfig requestConfig = requstConfigCache.get(timeout);
if (requestConfig == null) {
lock.lock();
try {
requestConfig = requstConfigCache.get(timeout);
if (requestConfig == null) {
requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(httpClientConfig.getConnectionRequestTimeout())
.setConnectTimeout(httpClientConfig.getConnectionTimeout())
.setSocketTimeout(timeout).build();
requstConfigCache.put(timeout, requestConfig);
}
} finally {
lock.unlock();
}
}
return requestConfig;
}
public RequestConfig getRequestConfig()
{
return getRequestConfig(httpClientConfig.getDefaultSocketTimeout());
}
private void init() {
if (httpClient == null) {
lock.lock();
try {
if (httpClient == null) {
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(httpClientConfig.getMaxTotal());
connectionManager.setDefaultMaxPerRoute(httpClientConfig.getDefaultMaxPerRoute());
connectionManager.closeExpiredConnections();
httpClient = HttpClientBuilder.create()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(getRequestConfig())
.disableCookieManagement()
.disableAutomaticRetries()
.build();
}
} finally {
lock.unlock();
}
}
}
public PoolStats getConnectionStatus(URI uri) {
init();
if (connectionManager != null) {
HttpHost target = URIUtils.extractHost(uri);
if (target.getPort() <= 0) {
try {
target = new HttpHost(
target.getHostName(),
DefaultSchemePortResolver.INSTANCE.resolve(target),
target.getSchemeName());
} catch (Throwable ignore) {
target = null;
}
}
if (target != null)
{
return connectionManager.getStats(new HttpRoute(target));
}
}
return null;
}
public String execute(HttpRequestBase request) throws Exception {
byte[] bytes = executeAndReturnByte(request);
if (bytes == null || bytes.length == 0) return null;
return new String(bytes, DEFAULT_CHARSET);
}
public byte[] executeAndReturnByte(HttpRequestBase request) throws Exception {
init();
HttpEntity entity = null;
CloseableHttpResponse resp = null;
byte[] rtn = new byte[0];
if (request == null) return rtn;
try {
resp = httpClient.execute(request);
entity = resp.getEntity();
if (resp.getStatusLine().getStatusCode() == 200) {
String encoding = ("" + resp.getFirstHeader("Content-Encoding")).toLowerCase();
if (encoding.indexOf("gzip") > 0) {
entity = new GzipDecompressingEntity(entity);
}
rtn = EntityUtils.toByteArray(entity);
} else {
logger.warn(request.getURI().toString()+" return error {}");
}
} catch (Exception e) {
logger.error(request.getURI().toString() + " " + e.getMessage());
throw e;
} finally {
EntityUtils.consumeQuietly(entity);
if (resp != null) {
try {
resp.close();
} catch (Exception ignore) {
}
}
}
return rtn;
}
public static String doGet(String url, Map<String, String> paramMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if (paramMap != null) {
for (String key : paramMap.keySet()) {
builder.addParameter(key, paramMap.get(key));
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
if (paramMap != null) {
List<NameValuePair> paramList = new ArrayList();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
httpPost.setConfig(builderRequestConfig());
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url, String json) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(builderRequestConfig());
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity requestEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
private static RequestConfig builderRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(TIMEOUT_MSEC)
.setConnectionRequestTimeout(TIMEOUT_MSEC)
.setSocketTimeout(TIMEOUT_MSEC).build();
}
public static String doPostJson(String url, Map<String, Object> paramMap) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(paramMap);
StringEntity entity = new StringEntity(json, "UTF-8");
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json");
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} finally {
if (response != null) {
response.close();
}
httpClient.close();
}
return resultString;
}
}
上手使用:Post请求 json嵌套
public void sentMessage(String accessToken, String msgId, String userId, String message, String openKfId, Long id){
HashMap<String, Object> sentMap = new HashMap<>();
String SENDING_MESSAGE_ADDRESS_URL = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token=";
HashMap<String, String> textMap = new HashMap<>();
sentMap.put("touser", userId);
sentMap.put(CustomerConstant.OPEN_KFID, openKfId);
sentMap.put("msgid", msgId);
sentMap.put("msgtype", "text");
textMap.put("content", message);
sentMap.put("text", textMap);
String sentMessageUrl = CustomerConstant.SENDING_MESSAGE_ADDRESS_URL + accessToken;
sentJson = doPostJson(sentMessageUrl, sentMap);
}
上手使用:发送POST请求
public String changeSession(String openKfId, String userId, String service_state, String servicer_userid) throws IOException {
String accessToken = getAccessToken(wechatCustomerConfig.getCorpId(), wechatCustomerConfig.getCorpSecret());
JSONObject jsonParams = new JSONObject();
String url = CustomerConstant.CHANGE_SESSION_URL + accessToken;
jsonParams.put(CustomerConstant.OPEN_KFID, openKfId);
jsonParams.put(CustomerConstant.EXTERNAL_USERID, userId);
jsonParams.put(CustomerConstant.SERVICE_STATE, service_state);
jsonParams.put(CustomerConstant.SERVICER_USERID, servicer_userid);
JSONObject jsonObject = JSON.parseObject(doPost(url, jsonParams.toJSONString()));
log.info("改变会话回调:{}", jsonObject);
return null;
}