HttpClient工具类

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 static HttpClient INSTANCE1 = null;
    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() {
    	if(INSTANCE1==null){
    		synchronized (LOCKS) {
    			if(INSTANCE1==null){
    				INSTANCE1 = new HttpClient(new DefaultHttpClientConfig());
    			}
			}
    	}
        return INSTANCE1;
    }*/
    
    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;
    }

    /*
     * timeout:socket超时时间,毫秒;不设置请求超时时间,则默认为2000;
     */
    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())//连接一个url的连接等待时间(连接超时)
                            .setSocketTimeout(timeout).build();//连接上一个url,获取response的返回等待时间(请求超时)
                    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());//设置整个连接池最大连接数
                    /**
                     * 根据连接到的主机对MaxTotal的一个细分;比如:
						MaxtTotal=400 DefaultMaxPerRoute=200
					         只连接到http://sishuok.com时,到这个主机的并发最多只有200;而不是400;
						当连接到http://sishuok.com 和 http://qq.com时,
						到每个主机的并发最多只有200;即加起来是400(但不能超过400);
						所以起作用的设置是DefaultMaxPerRoute。
                     */
                    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;
    }

    /**
     * 发送GET方式请求
     * @param url 地址
     * @param paramMap 参数
     */
    public static String doGet(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象
        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 {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            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());

            // 执行http请求
            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;
    }
    /**
     * 发送POST请求
     * @param url
     * @return
     * @throws IOException
     */
    public static String doPost(String url, String json) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(builderRequestConfig());
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

            // 设置 JSON 字符串为请求体
            StringEntity requestEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e; // You may want to log the exception or handle it accordingly
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace(); // You may want to log the exception or handle it accordingly
            }
            try {
                httpClient.close(); // Don't forget to close the httpClient
            } catch (IOException e) {
                e.printStackTrace(); // You may want to log the exception or handle it accordingly
            }
        }

        return resultString;
    }

    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }

    /**
     * Post请求 json嵌套
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPostJson(String url, Map<String, Object> paramMap) throws IOException {
        // 创建Httpclient对象
        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;

    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值