Java Http连接池封装

//基本参数
package com.linoer.app.http
public class HttpConfig {

	private int maxTotal=100;
	private int defaultMaxPerRoute=10;
	private int maxPerRoute=100;
	private int socketTimeout=5000;
	private int connectTimeout=50000;
	private int connectionRequestTimeout=5000;
	private String protocol="http";
	private boolean authentication=false;
	private boolean authType;
	private String keyStore;
	private String trustStore;
	private String keyStorepass;
	private String trustStorepass;
	private String algorithm;
	private String charSet="UTF-8";
	
	public int getMaxTotal() {
		return maxTotal;
	}
	public void setMaxTotal(int maxTotal) {
		this.maxTotal = maxTotal;
	}
	
	public int getDefaultMaxPerRoute() {
		return defaultMaxPerRoute;
	}
	public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {
		this.defaultMaxPerRoute = defaultMaxPerRoute;
	}
	public int getMaxPerRoute() {
		return maxPerRoute;
	}
	public void setMaxPerRoute(int maxPerRoute) {
		this.maxPerRoute = maxPerRoute;
	}
	public int getSocketTimeout() {
		return socketTimeout;
	}
	public void setSocketTimeout(int socketTimeout) {
		this.socketTimeout = socketTimeout;
	}
	public int getConnectTimeout() {
		return connectTimeout;
	}
	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}
	public int getConnectionRequestTimeout() {
		return connectionRequestTimeout;
	}
	public void setConnectionRequestTimeout(int connectionRequestTimeout) {
		this.connectionRequestTimeout = connectionRequestTimeout;
	}
	
	
	public String getProtocol() {
		return protocol;
	}
	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}
	public boolean isAuthentication() {
		return authentication;
	}
	public void setAuthentication(boolean authentication) {
		this.authentication = authentication;
	}
	public boolean isAuthType() {
		return authType;
	}
	public void setAuthType(boolean authType) {
		this.authType = authType;
	}
	public String getKeyStore() {
		return keyStore;
	}
	public void setKeyStore(String keyStore) {
		this.keyStore = keyStore;
	}
	public String getTrustStore() {
		return trustStore;
	}
	public void setTrustStore(String trustStore) {
		this.trustStore = trustStore;
	}
	public String getKeyStorepass() {
		return keyStorepass;
	}
	public void setKeyStorepass(String keyStorepass) {
		this.keyStorepass = keyStorepass;
	}
	public String getTrustStorepass() {
		return trustStorepass;
	}
	public void setTrustStorepass(String trustStorepass) {
		this.trustStorepass = trustStorepass;
	}
	public String getAlgorithm() {
		return algorithm;
	}
	public void setAlgorithm(String algorithm) {
		this.algorithm = algorithm;
	}
	public String getCharSet() {
		return charSet;
	}
	public void setCharSet(String charSet) {
		this.charSet = charSet;
	}
	
	

}



//连接池的构建
package com.linoer.app.http;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * http连接池
 */
public class HttpPool {
	
	private PoolingHttpClientConnectionManager poolConnection = new PoolingHttpClientConnectionManager();
	
	private HttpConfig httpConfig ;
	private CloseableHttpClient httpclient;

	
	public void init(){
		poolConnection.setMaxTotal(httpConfig.getMaxTotal());
		poolConnection.setDefaultMaxPerRoute(httpConfig.getMaxPerRoute());
		poolConnection.setDefaultMaxPerRoute(httpConfig.getDefaultMaxPerRoute());
		this.httpclient = HttpClients.custom().setConnectionManager(poolConnection).build();
	}
	
	/**
	 * 获取连接
	 */
	public CloseableHttpClient getHttpClient(){
		
	    return this.httpclient;
	}

	public HttpConfig getHttpConfig() {
		return httpConfig;
	}

	public void setHttpConfig(HttpConfig httpConfig) {
		this.httpConfig = httpConfig;
	}
	
}


//发送请求

package com.linoer.app.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * HTTP消息发送
 */
public class HttpSend {

    private Logger log = LoggerFactory.getLogger(getClass());

    private HttpPool httpPool;
    /**
     * HTTP消息发送
     * @param xml              报文参数
     * @param url              发送地址
     * @param charset          发送字符集
     * @param maxSendTimes     最大发送次数
     * @param sendIntervalTime 重复发送间隔时间
     * @return TimeOut:超时标识
     */
    public String send(String xml, String url, String charset, int maxSendTimes, int sendIntervalTime, int type){
        log.debug("Http Send,请求地址:" + url);
        log.debug("Http Send,字符集:" + charset);
        CloseableHttpClient httpClient = null;
        String retStr = "";
        int sendTimes = 0;
        do {
            try {
                if (type == 0) {
                    httpClient = httpPool.getHttpClient(); //http请求
                } else {
                    httpClient = HttpsPostUtil.createHttpsClient(); //https请求,发给基金公司
                }
                HttpPost httpPost = new HttpPost(url);
                log.debug("Http Send,请求报文为:" + xml);
                StringEntity stringEntity = new StringEntity(xml, charset);
                httpPost.setEntity(stringEntity);
                httpPost.setConfig(getRequestConfig());
                log.debug("Http Send,开始第" + (sendTimes + 1) + "次发送...");
                HttpResponse httpResponse = httpClient.execute(httpPost);
                log.debug("Http Send,发送完成,总调用次数为:" + (sendTimes + 1) + "次");
                HttpEntity responseEntity = httpResponse.getEntity();
                retStr = EntityUtils.toString(responseEntity, charset);
                log.debug("Http Send,返回报文:" + retStr);
                EntityUtils.consume(responseEntity);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode >= 200 && statusCode < 300) {
                    log.debug("Http Send,第" + (sendTimes + 1) + "次调用成功,返回码为:[" + statusCode + "]");
                    break;
                } else {
                    retStr = "";
                    log.error("Http Send,第" + (sendTimes + 1) + "次调用出错,返回码为:[" + statusCode + "]");
                    if (sendTimes + 1 <= maxSendTimes) {
                        log.debug("Http Send," + (sendIntervalTime / 1000) + "秒后,重新发起请求...");
                        Thread.sleep(sendIntervalTime);
                    } else {
                        log.debug("Http Send,达到重发最大次数,退出程序!");
                    }
                }
            } catch (ClientProtocolException e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错:ClientProtocolException", e);
                retStr = null;
            } catch (SocketTimeoutException e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错: SocketTimeoutException", e);
                retStr = null;
            } catch (IOException e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错: IOException", e);
                retStr = null;
            } catch (Exception e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错", e);
                retStr = null;
            } finally {
                sendTimes++;
            }
        } while (sendTimes < maxSendTimes);
        return retStr;
    }

    /**
     * HTTP消息发送
     * @param param            报文参数
     * @param url              发送地址
     * @param charset          发送字符集
     * @param maxSendTimes     最大发送次数
     * @param sendIntervalTime 重复发送间隔时间
     * @return
     */
    public String send(Map<String, String> param, String url, String charset, int maxSendTimes, int sendIntervalTime, int type) throws Exception {
        log.debug("Http Send,请求地址:" + url);
        log.debug("Http Send,字符集:" + charset);
        CloseableHttpClient httpClient = null;
        String retStr = "";
        int sendTimes = 0;
        do {
            try {
                if (type == 0) {
                    httpClient = httpPool.getHttpClient();
                } //http请求
                else {
                    httpClient = HttpsPostUtil.createHttpsClient();
                }//https请求,发给基金公司
                HttpPost httpPost = new HttpPost(url);
                log.debug("Http Send,请求报文为:" + param);
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                Set<String> sortSet = param.keySet();
                for (String key : sortSet) {
                    formParams.add(new BasicNameValuePair(key, param.get(key)));
                }
                HttpEntity entityForm = new UrlEncodedFormEntity(formParams, charset);
                httpPost.setEntity(entityForm);
                httpPost.setConfig(getRequestConfig());
                log.debug("Http Send,开始第" + (sendTimes + 1) + "次发送...");
                HttpResponse httpResponse = httpClient.execute(httpPost);
                log.debug("Http Send,发送完成,总调用次数为:" + (sendTimes + 1) + "次");

                HttpEntity responseEntity = httpResponse.getEntity();
                retStr = EntityUtils.toString(responseEntity, charset);
                log.debug("Http Send,返回报文:" + retStr);
                EntityUtils.consume(responseEntity);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode >= 200 && statusCode < 300) {
                    log.debug("Http Send,第" + (sendTimes + 1) + "次调用成功,返回码为:[" + statusCode + "]");
                    break;
                } else {
                    retStr = "";
                    log.error("Http Send,第" + (sendTimes + 1) + "次调用出错,返回码为:[" + statusCode + "]");
                    if (sendTimes + 1 <= maxSendTimes) {
                        log.debug("Http Send," + (sendIntervalTime / 1000) + "秒后,重新发起请求...");
                        Thread.sleep(sendIntervalTime);
                    } else {
                        log.debug("Http Send,达到重发最大次数,退出程序!");
                    }
                }
            } catch (ClientProtocolException e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错:ClientProtocolException", e);
                retStr = null;
            } catch (SocketTimeoutException e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错: SocketTimeoutException", e);
                if (sendTimes + 1 >=maxSendTimes) {
                    throw new Exception(e);
                } else {
                    retStr = null;
                }
            } catch (IOException e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错: IOException", e);
                retStr = null;
            } catch (Exception e) {
                log.error("Http Send,第" + (sendTimes + 1) + "次调用出错", e);
                retStr = null;
            } finally {
                sendTimes++;
            }
        } while (sendTimes < maxSendTimes);
        return retStr;
    }


    /**
     * 获取请求配置
     *
     * @return
     */
    public RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setSocketTimeout(httpPool.getHttpConfig().getSocketTimeout())
                .setConnectTimeout(httpPool.getHttpConfig().getConnectTimeout())
                .setConnectionRequestTimeout(
                        httpPool.getHttpConfig().getConnectionRequestTimeout())
                .build();
    }

    public HttpPool getHttpPool() {
        return httpPool;
    }

    public void setHttpPool(HttpPool httpPool) {
        this.httpPool = httpPool;
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值