简单封装的httpclient

package com.<span style="font-family: Arial, Helvetica, sans-serif;">****</span><span style="font-family: Arial, Helvetica, sans-serif;">.util;</span>


import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.List;

import javax.net.ssl.SSLContext;

import me.***.elog.Log;
import me.***.elog.LogFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.****.weixin.common.WeixinConstant;




public class HttpCallTool {
	
	Log log = LogFactory.getLog(HttpCallTool.class);

    //连接超时时间,默认10秒
    private int socketTimeout = 10000;

    //传输超时时间,默认30秒
    private int connectTimeout = 30000;

    //请求器的配置
    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();;

    //HTTP请求器
    private HttpClient httpClient;
    
	public HttpCallTool(String payType,String tradeType) throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException{
			 init(payType,tradeType);
	}
	public HttpCallTool(){
		httpClient = HttpClients.createDefault();
	}
    @SuppressWarnings("deprecation")
	private void init(String payType,String tradeType) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {

	        KeyStore keyStore = KeyStore.getInstance("PKCS12");
	        InputStream instream =null;
	        SSLContext sslcontext=null;
	        try{
	        	if("weixin".equals(payType)){
		        	 if("JSAPI".equals(tradeType)){
		        		 instream = HttpCallTool.class.getResourceAsStream(WeixinConstant.getCertLocalPath());//加载本地的证书进行https加密传输
		     	         keyStore.load(instream, WeixinConstant.getCertPassword().toCharArray());//设置证书密码
		    			  sslcontext = SSLContexts.custom()
		    	                .loadKeyMaterial(keyStore, WeixinConstant.getCertPassword().toCharArray())
		    	                .build();
		        	 }else if("APP".equals(tradeType)){
		        		 instream = HttpCallTool.class.getResourceAsStream(WeixinConstant.getCertLocalPathForApp());//加载本地的证书进行https加密传输
		     	         keyStore.load(instream, WeixinConstant.getCertPasswordForApp().toCharArray());//设置证书密码
		    			 sslcontext = SSLContexts.custom()
		    	                .loadKeyMaterial(keyStore, WeixinConstant.getCertPasswordForApp().toCharArray())
		    	                .build();
		        	 }
		        }
	        } catch (CertificateException e) {
 	        	log.error(e.getMessage(),e);
 	        } catch (NoSuchAlgorithmException e) {
 	        	log.error(e.getMessage(),e);
 	        } finally {
 	            instream.close();
 	        }
	        // Trust own CA and all self-signed certs
	       
	        // Allow TLSv1 protocol only
	        
			@SuppressWarnings("deprecation")
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
	                sslcontext,
	                new String[]{"TLSv1"},
	                null,
	                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			ConnectionConfig connectionConfig = ConnectionConfig.custom()
	                .setBufferSize(4128)
	                .build();
	        httpClient = HttpClients.custom().setDefaultConnectionConfig(connectionConfig).setSSLSocketFactory(sslsf).build();
	    }

	//发送key - value数据
	public  String callService(List<NameValuePair> list,String url) throws Exception{
		
		String responseStr="";
		try {
			HttpPost httpPost = new HttpPost(url);
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,HTTP.UTF_8);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
			entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()));
			httpPost.setEntity(entity);
			log.info("rpc请求开始:" + httpPost.getURI());
			HttpResponse response = httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entityReponse = response.getEntity();
				if (entityReponse != null)
				{
					responseStr=Util.readStream(entityReponse.getContent(), "utf-8");
					log.info(responseStr);
				}else{
					throw new Exception("请求结果为空!");
				}
			}
		} catch (Exception e) {
			log.error("通信失败",e);
			throw new Exception("请求超时!");
		}finally{
			httpClient.getConnectionManager().shutdown(); 
		}
		return responseStr;
	}
	//发送json数据
	public  String callService(String httpJsonMessage,String url) throws Exception{
		String responseStr="";
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity entity = new StringEntity(httpJsonMessage, "utf-8");
			entity.setContentType("application/json");
			httpPost.setEntity(entity);
			log.info("rpc请求开始:" + httpPost.getURI());
			HttpResponse response = httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entityReponse = response.getEntity();
				if (entityReponse != null)
				{
					responseStr=Util.readStream(entityReponse.getContent(), "utf-8");
					log.info(responseStr);
				}else{
					throw new Exception("请求结果为空!");
				}
			}
		} catch (Exception e) {
			log.error("通信失败",e);
			throw new Exception("请求超时!");
		}finally{
			httpClient.getConnectionManager().shutdown(); 
		}
		return responseStr;
	}
	
	//发送json数据
	  public  String callGetService(String url) throws Exception{
			String responseStr="";
			try {
				HttpGet httpGet = new HttpGet(url);
				HttpResponse response = httpClient.execute(httpGet);
				if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
					HttpEntity entityReponse = response.getEntity();
					if (entityReponse != null)
					{
						responseStr=Util.readStream(entityReponse.getContent(), "utf-8");
						log.info(responseStr);
					}else{
						throw new Exception("请求结果为空!");
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage());
				throw new Exception("请求超时!");
			}finally{
				httpClient.getConnectionManager().shutdown(); 
			}
			return responseStr;
		}
	//发送xml报文数据
	public String sendPost(String url, String postDataXml) {
		
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        //得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(postDataXml, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("Host", "api.mch.weixin.qq.com");
        httpPost.setEntity(postEntity);

        //设置请求器的配置
        httpPost.setConfig(requestConfig);

        log.info("executing request" + httpPost.getRequestLine());

        try {
            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity, "UTF-8");

        } catch (ConnectionPoolTimeoutException e) {
            log.error("http get throw ConnectionPoolTimeoutException(wait time out)",e);

        } catch (ConnectTimeoutException e) {
        	log.error("http get throw ConnectTimeoutException",e);

        } catch (SocketTimeoutException e) {
        	log.error("http get throw SocketTimeoutException",e);

        } catch (Exception e) {
        	log.error("http get throw Exception",e);

        } finally {
            httpPost.abort();
        }

        return result;
    
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值