Java的HttpClient封装http通信工具类

目的与初衷

最近在工作中需要在后台调用第三方接口(微信,支付,华为点击回拨,三通一达物流快递接口),最近在学习Kotlin,尝试使用Kotlin和HttpClient,自己封装了一个HttpClient工具类,封装常用实现get,post工具方法类

1 什么是HttpClient

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是Apache HttpComponents 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

2 功能介绍

  • 支持自动转向
  • 支持 HTTPS 协议
  • 支持代理服务器等

3. 版本比较

注意本篇博客主要是基于 HttpClient4.5.5 版本的来讲解的,也是现在最新的版本,之所以要提供版本说明的是因为 HttpClient 3 版本和 HttpClient 4 版本差别还是很多大的,基本HttpClient里面的接口都变了,你把 HttpClient 3 版本的代码拿到 HttpClient 4 上面都运行不起来,会报错的。所以一定要注意 HtppClient 的版本问题。

4. HttpClient不能做的事情

HttpClient 不是浏览器,它是一个客户端 HTTP 协议传输类库。HttpClient 被用来发送和接受 HTTP 消息。HttpClient 不会处理 HTTP 消息的内容,不会进行 javascript 解析,不会关心 content type,如果没有明确设置,HttpClient 也不会对请求进行格式化、重定向 url,或者其他任何和 HTTP 消息传输相关的功能。

5. HttpClient使用流程

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

    1. 创建HttpClient对象。
    1. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
    1. 如果需要发送请求参数,可调用HttpGetsetParams方法来添加请求参数;对于HttpPost对象而言,可调用setEntity(HttpEntity entity)方法来设置请求参数。
    1. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse对象。
    1. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
    1. 释放连接。无论执行方法是否成功,都必须释放连接

6、 HttpClient与Java结合使用

 

/**
 * @Description httpclient客户端请求处理的通用类  
 * @ClassName   HttpClientUtls  
 * @Date        2017年6月6日 上午11:41:36  
 * @Copyright (c) All Rights Reserved, 2017.
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);  
    private final static int CONNECT_TIMEOUT = 7000; // in milliseconds
    private final static String DEFAULT_ENCODING = "UTF-8";
    private static RequestConfig requestConfig;  
    private static final int MAX_TIMEOUT = 7000;  
    private static PoolingHttpClientConnectionManager connMgr;  
    private static String LINE = System.getProperty("line.separator");//换行相当于\n
    
    static {  
        // 设置连接池  
        connMgr = new PoolingHttpClientConnectionManager();  
        // 设置连接池大小  
        connMgr.setMaxTotal(100);  
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());  
  
        RequestConfig.Builder configBuilder = RequestConfig.custom();  
        // 设置连接超时  
        configBuilder.setConnectTimeout(MAX_TIMEOUT);  
        // 设置读取超时  
        configBuilder.setSocketTimeout(MAX_TIMEOUT);  
        // 设置从连接池获取连接实例的超时  
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);  
        // 在提交请求之前 测试连接是否可用  
        configBuilder.setStaleConnectionCheckEnabled(true);  
        requestConfig = configBuilder.build();  
    }
    
    
    /**
     * @Description get请求链接  
     * @Date        2017年6月6日 上午11:36:09  
     * @param rURL
     * @return 参数  
     * @return String 返回类型   
     * @throws
     */
    public static String get(String rURL) {
        String result = "";
        try {
            URL url = new URL(rURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(60000);//将读超时设置为指定的超时,以毫秒为单位。用一个非零值指定在建立到资源的连接后从 Input 流读入时的超时时间。如果在数据可读取之前超时期满,则会引发一个 java.net.SocketTimeoutException。
            con.setDoInput(true);//指示应用程序要从 URL 连接读取数据。
            con.setRequestMethod("GET");//设置请求方式
            if(con.getResponseCode() == 200){//当请求成功时,接收数据(状态码“200”为成功连接的意思“ok”)
                InputStream is = con.getInputStream();
                result = formatIsToString(is);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }
    
    /**
     * 
     * @Description POST请求   
     * @Date        2017年6月6日 上午11:36:28  
     * @param postUrl
     * @param params
     * @return 参数  
     * @return String 返回类型   
     * @throws
     */
    public static String post(String postUrl, Map params){
        StringBuffer sb = new StringBuffer();
        String line;
        try {
            URL url = new URL(postUrl);
            URLConnection urlConn = url.openConnection();
            HttpURLConnection httpUrlConn = (HttpURLConnection)urlConn;
            
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            
            httpUrlConn.setRequestMethod("POST");
            OutputStreamWriter wr = new OutputStreamWriter(httpUrlConn.getOutputStream());
            String content = getConcatParams(params);
            wr.write(content);
            wr.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(),"utf-8"));
            while((line = in.readLine()) != null){
                sb.append(line);
            }
            wr.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    /**
     * 
     * @Description 获取参数内容   
     * @Date        2017年6月6日 上午11:36:50  
     * @throws UnsupportedEncodingException 参数  
     * @return String 返回类型   
     * @throws
     */
    public static String getConcatParams(Map params) throws UnsupportedEncodingException {
        String content = null;
        Set> set = params.entrySet();//Map.entrySet 方法返回映射的 collection 视图,其中的元素属于此类
        StringBuilder sb = new StringBuilder();
        for(Entry i: set){
            //将参数解析为"name=tom&age=21"的模式
            sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue().toString(), "utf-8")).append("&");
        }
        if(sb.length() > 1){
            content = sb.substring(0, sb.length()-1);
        }
        return content;
    }
    
    

    public static String formatIsToString(InputStream is)throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        try {
            while( (len=is.read(buf)) != -1){
                baos.write(buf, 0, len);
            }
            baos.flush();
            baos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(baos.toByteArray(),"utf-8");
    }
    
     /**
     * @Description 拼接请求参数  
     * @Date        2017年5月24日 上午10:39:28  
     * @param @return 参数  
     * @return String 返回结果如:  userName=1111&passWord=222  
     * @throws
     */
    private static String getContent(Map params, String encoding) throws UnsupportedEncodingException {
        String content = null;
        Set> set = params.entrySet();//Map.entrySet 方法返回映射的 collection 视图,其中的元素属于此类
        StringBuilder sb = new StringBuilder();
        for(Entry i: set){
            //将参数解析为"name=tom&age=21"的模式
            sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue().toString(), encoding)).append("&");
        }
        if(sb.length() > 1){
            content = sb.substring(0, sb.length()-1);
        }
        return content;
    }
    
    public static String post(String postUrl, Map params, String encoding){
        StringBuffer sb = new StringBuffer();
        String line;
        try {
            URL url = new URL(postUrl);
            URLConnection urlConn = url.openConnection();
            HttpURLConnection httpUrlConn = (HttpURLConnection)urlConn;
            
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            
            httpUrlConn.setRequestMethod("POST");
            OutputStreamWriter wr = new OutputStreamWriter(httpUrlConn.getOutputStream());
            String content = getContent(params, encoding);
            wr.write(content);
            wr.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(httpUrlConn.getInputStream(), encoding));
            while((line = in.readLine()) != null){
                sb.append(line);
            }
            wr.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    
    public static String get(String rURL, String encoding) {
        String result = "";
        
        try {
            URL url = new URL(rURL);
            
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setReadTimeout(180000);//将读超时设置为指定的超时,以毫秒为单位。用一个非零值指定在建立到资源的连接后从 Input 流读入时的超时时间。如果在数据可读取之前超时期满,则会引发一个 java.net.SocketTimeoutException。
            con.setDoInput(true);//指示应用程序要从 URL 连接读取数据。
            con.setRequestMethod("GET");//设置请求方式
            if(con.getResponseCode() == 200){//当请求成功时,接收数据(状态码“200”为成功连接的意思“ok”)
                InputStream is = con.getInputStream();
                result = formatIsToString(is, encoding);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }
    
    /**
     * 
     * @Description 格式字符串  
     * @Date        2017年6月6日 上午11:39:23  
     * @param is
     * @param encoding
     * @return
     * @throws Exception 参数  
     * @return String 返回类型   
     * @throws
     */
    public static String formatIsToString(InputStream is, String encoding) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        try {
            while( (len=is.read(buf)) != -1){
                baos.write(buf, 0, len);
            }
            baos.flush();
            baos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(baos.toByteArray(), encoding);
    }
    
    
      /**
     * @Description HttpUrlConnection  
     * @Author      liangjilong  
     * @Date        2017年5月17日 上午10:53:00  
     * @param urlStr
     * @param data
     * @param contentType
     * @param requestMethod
     * @param 参数  
     * @return String 返回类型   
     * @throws
     */
    public static String createHttp(String reqUrl, String reqBodyParams, String contentType,String requestMethod){
        
        BufferedReader reader = null;
        HttpURLConnection  conn =null;
         try {
             URL url = new URL(reqUrl);
             conn = (HttpURLConnection) url.openConnection();  
             conn.setDoOutput(true);
             conn.setDoInput(true);
             conn.setUseCaches(false);
             conn.setConnectTimeout(CONNECT_TIMEOUT);
             conn.setReadTimeout(CONNECT_TIMEOUT);
             conn.setRequestMethod(requestMethod);
             conn.connect();  
             InputStream inputStream = conn.getInputStream();
             if(contentType != null){
                 conn.setRequestProperty("Content-type", contentType);
             }
             if(reqBodyParams!=null){
                 OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
                 writer.write(reqBodyParams); 
                 writer.flush();
                 writer.close();  
             }
             reader = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_ENCODING));
             StringBuilder sb = new StringBuilder();
             String line = null;
             while ((line = reader.readLine()) != null) {
                 sb.append(line);
                 sb.append("\r\n");//\r是回车\n是换行
             }
             logger.info("请求链接为:"+reqUrl+"返回的数据为"+sb.toString());
             return sb.toString();
             
         } catch (IOException e) {
             logger.error("Error connecting to " + reqUrl + ": " + e.getMessage());
         } finally {
             try {
                 if (reader != null){
                     reader.close();
                 }
                 if (conn != null){
                     conn.disconnect();
                 }
             } catch (IOException e) {
                  logger.error("Error connecting to finally" + reqUrl + ": " + e.getMessage());
             }
         }
         return null;
     }
    
  
    /**
     * 
     * @Description 建立http请求链接支持SSL请求 
     * @Date        2017年6月6日 上午11:11:56  
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @param headerMap请求头属性,可以为空
     * @param isSsl 当isSSL=true的时候支持Https处理,当isSSL=false的时候http请求
     * @param sslVersion  支持https的版本参数
     * @return 参数  
     * @return String 返回类型   
     * @throws
     */
    public static String createHttps(String requestUrl, String requestMethod,Map headerMap,
            boolean isSsl,String sslVersion,String bodyParams) {
        HttpsURLConnection conn = null ;
        BufferedReader bufferedReader =null;
        InputStreamReader inputStreamReader =null; 
        InputStream inputStream = null;
        try {
            SSLSocketFactory ssf = null;
            if(isSsl){
                //这行代码必须要在创建URL对象之前,因为先校验SSL的https请求通过才可以访问http
                ssf = SSLContextSecurity.createIgnoreVerifySSL(sslVersion);
            }
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            URL url = new URL(requestUrl);
         
            conn = (HttpsURLConnection) url.openConnection();
            if(isSsl){
                conn.setSSLSocketFactory(ssf);
            }
            conn.setDoOutput(true);//输出
            conn.setDoInput(true);//输入
            conn.setUseCaches(false);//是否支持缓存
            
            /*设置请求头属性和值 */
            if(headerMap!=null && !headerMap.isEmpty()){
                 for (String key : headerMap.keySet()) {
                     Object value = headerMap.get(key);
                     //如:conn.addRequestProperty("Authorization","123456");
                     conn.addRequestProperty(key,String.valueOf(value));
                 }
            }
            
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            // 当设置body请求参数
            if (!ObjectUtil.isEmpty(bodyParams)) {  
                DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());  
                outStream.write(bodyParams.getBytes("UTF-8"));  
                outStream.close();
                outStream.flush(); 
            } 

            if(conn!=null && conn.getResponseCode()==200){
                // 从输入流读取返回内容
                inputStream = conn.getInputStream();
                inputStreamReader= new InputStreamReader(inputStream, "UFT-8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                StringBuffer buffer = new StringBuffer();
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                    buffer.append("\r").append(LINE);
                }
                return buffer.toString();
            }else{
                return "FAIL";
            }
        } catch (ConnectException ce) {
            logger.error("连接超时:{}",  ce+"\t请求链接"+requestUrl);
        } catch (Exception e) {
            logger.error("https请求异常:{}", e+"\t请求链接"+requestUrl);
            return "FAIL";//请求系统频繁
        }finally{
            // 释放资源
            try {
                if(conn!=null){conn.disconnect();}
                if(bufferedReader!=null){bufferedReader.close();}
                if(inputStreamReader!=null){inputStreamReader.close();}
                if(inputStream!=null){
                    inputStream.close();
                    inputStream = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
    
    
     /** 
     * 发送 POST 请求(HTTP),JSON形式 
     * @Author      liangjilong  
     * @Date        2017年5月22日 下午3:57:03  
     * @param @param apiUrl
     * @param @param json
     * @param @param contentType
     * @param @return 参数  
     * @return String 返回类型   
     * @throws
     */
    public static String httpClientPost(String reqUrl, Object reqBodyParams,String contentType,String encoding,Map headerMap) {  
        String  result ="";  
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        HttpPost httpPost = new HttpPost(reqUrl);  
        
        /*设置请求头属性和值 */
        if(headerMap!=null && !headerMap.isEmpty()){
             for (String key : headerMap.keySet()) {
                 Object value = headerMap.get(key);
                 //如: httpPost.addHeader("Content-Type", "application/json");  
                 httpPost.addHeader(key,String.valueOf(value));
             }
        }
       
        CloseableHttpResponse response = null;  
        try {  
            httpPost.setConfig(requestConfig);  
            if(reqBodyParams!=null){
                logger.info(getCurrentClassName()+".httpClientPost方法返回的参数为:"+reqBodyParams.toString());
                StringEntity stringEntity = new StringEntity(reqBodyParams.toString(),(encoding==null||"".equals(encoding)?"utf-8":encoding));//解决中文乱码问题  
                if(encoding!=null && encoding!=""){
                    stringEntity.setContentEncoding(encoding);  
                }
                if(contentType!=null && contentType!=""){
                    stringEntity.setContentType(contentType);  
                }
                httpPost.setEntity(stringEntity);  
                
            }
            response = httpClient.execute(httpPost);  
            HttpEntity entity = response.getEntity();  
            if (entity != null && response.getStatusLine().getStatusCode()==200) {
                //Attempted read from closed stream,因为EntityUtils.toString(HttpEntity)方法被使用了多次。所以每个方法内只能使用一次。
                //httpStr = EntityUtils.toString(entity, "UTF-8");  
                String buffer = IoUtils.getInputStream(entity.getContent());
                logger.info("HttpUrlPost的entity返回的信息为:"+buffer.toString());
                return buffer.toString();//返回  
            }else{
                logger.error("HttpUrlPost的entity对象为空");
                return result;
            }
        } catch (IOException e) {
            logger.error("HttpUrlPost出现异常,异常信息为:"+e.getMessage());
            e.printStackTrace();  
        } finally { 
             if(response != null){  
                 try {  
                     response.close();  
                 } catch (IOException e) {  
                     e.printStackTrace();  
                 }  
             }  
             if(httpClient != null){  
                 try {  
                     httpClient.close();  
                 } catch (IOException e) {  
                     e.printStackTrace();  
                 }  
             }  
        }  
        return result;  
    }  
    

    /** 
    * @Description  发送 POST 请求(HTTP),JSON形式   
    * @Author      liangjilong 
    * @throws
    */
   public static String httpClientPost(String reqUrl, Map reqBodyParams,String contentType,String encoding,Map headerMap) {  
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        return commonHttpClientPost(reqUrl, reqBodyParams, contentType, encoding, headerMap, httpClient);  
   }  
   
    
    
    /** 
     * @Description httpClientGet   
     * @Date        2017年5月22日 下午3:57:03  
     * @return String 返回类型   
     * @throws
     */
    public static String httpClientGet(String reqUrl, Map reqBodyParams,String contentType,String encoding,Map headerMap) {  
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        String httpStr = commonHttpClientGet(reqUrl, reqBodyParams, encoding,
                headerMap, httpClient);  
        return httpStr;  
    }

    /**
     * @Description reqParamStr  
     * @param reqBodyParams
     * @param encoding
     * @param reqParamStr
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException 参数  
     * @return String 返回类型
     */
    private static String reqParamStr(Map reqBodyParams, String encoding, String reqParamStr) throws IOException,
            UnsupportedEncodingException {
        if(reqBodyParams!=null && !reqBodyParams.isEmpty()){
            //封装请求参数  
            List params = new ArrayList();
            for (Map.Entry entry : reqBodyParams.entrySet()) {  
                String key = entry.getKey();
                Object val = entry.getValue();
                params.add(new BasicNameValuePair(key, val.toString())); 
            }
            reqParamStr = EntityUtils.toString(new UrlEncodedFormEntity(params,encoding));  
            //httpGet.setURI(new URIBuilder(httpGet.getURI().toString() + "?" + param).build());  
        }
        return reqParamStr;
    }  

    /**
     * @Description 创建httpClient  
     * @Date        2017年8月1日 上午10:26:29  
     * @return 参数  
     * @return CloseableHttpClient 返回类型
     */
    
    public static CloseableHttpClient createHttpClient() {
        SSLContext sslcontext = null;
        try {
            sslcontext = new SSLContextBuilder().loadTrustMaterial(null, 
            new TrustStrategy() 
            {   @Override
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                }
            }).build();
        } catch (KeyManagementException e) {
            return null;
        } catch (NoSuchAlgorithmException e) {
            return null;
        } catch (KeyStoreException e) {
            return null;
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, 
                new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;
    }
     
    
    
    /**
     * @Description 创建httpsPost  
     * @Date        2017年8月1日 上午10:29:09  
     * @param reqUrl
     * @param reqBodyParams
     * @param contentType
     * @param encoding
     * @param headerMap
     * @return 参数  
     * @return String 返回类型
     */
    public static String createHttpsPost(String reqUrl, Map reqBodyParams,String contentType,String encoding,Map headerMap) {  
        CloseableHttpClient httpClient = createHttpClient(); 
        return commonHttpClientPost(reqUrl, reqBodyParams, contentType, encoding, headerMap, httpClient);  
   }

    /**
    * 
     * @Description commonHttpClientPost  
     * @Date        2017年8月1日 上午10:34:43  
     * @param reqUrl
     * @param reqBodyParams
     * @param contentType
     * @param encoding
     * @param headerMap
     * @param httpClient
     * @return 参数  
     * @return String 返回类型
     */
    private static String commonHttpClientPost(String reqUrl, Map reqBodyParams, String contentType, String encoding, Map headerMap, CloseableHttpClient httpClient) {
        String  result ="";  
        CloseableHttpResponse response = null;  
    try {  
         HttpPost httpPost = new HttpPost(reqUrl);  
         String reqParamStr = "";
         /*设置请求头属性和值 */
         if(headerMap!=null && !headerMap.isEmpty()){
             for (String key : headerMap.keySet()) {
                 Object value = headerMap.get(key);
                 //如: httpPost.addHeader("Content-Type", "application/json");  
                 httpPost.addHeader(key,String.valueOf(value));
             }
         }
          reqParamStr = reqParamStr(reqBodyParams, encoding, reqParamStr);
         
          httpPost.setConfig(requestConfig);  
          if(reqParamStr!=null){
               StringEntity stringEntity = new StringEntity(reqParamStr.toString(),(encoding==null||"".equals(encoding)?"utf-8":encoding));//解决中文乱码问题  
               if(encoding!=null && encoding!=""){
                    stringEntity.setContentEncoding(encoding);  
               }
               if(contentType!=null && contentType!=""){
                    stringEntity.setContentType(contentType);  
               }
               httpPost.setEntity(stringEntity);  
           }
           response = httpClient.execute(httpPost);  
           HttpEntity entity = response.getEntity();  
           if (entity != null && response.getStatusLine().getStatusCode()==200) {
                String buffer = IoUtils.getInputStream(entity.getContent());
                logger.info(getCurrentClassName()+"#commonHttpClientPost,***reqUrl***:"+reqUrl+",***Response content*** : " + buffer.toString());
                return buffer.toString();//返回  
           }else{
                logger.error("commonHttpClientPost的entity对象为空");
                return result;
           }
       } catch (IOException e) {
        logger.error("HttpUrlPost出现异常,异常信息为:"+e.getMessage());
           e.printStackTrace();  
       } finally { 
         if(response != null){  
                try {  
                 response.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
         if(httpClient != null){  
                try {  
                 httpClient.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
       }  
       return result;
    }  
   
    
    /** 
     * @Description httpClientGet  
     * @Date        2017年5月22日 下午3:57:03  
     * @param apiUrl
     * @param json
     * @param contentType

     * @return String 返回类型   
     * @throws
     */
    public static String createHttpsGet(String reqUrl, Map reqBodyParams,String contentType,String encoding,Map headerMap) {  
        CloseableHttpClient httpClient = createHttpClient();  
        String httpStr = commonHttpClientGet(reqUrl, reqBodyParams, encoding, headerMap, httpClient);  
        return httpStr;  
    }
    
    /**
     * @Description commonHttpClientGet  
     * @Date        2017年8月1日 上午10:35:09  
     * @param reqUrl
     * @param reqBodyParams
     * @param encoding
     * @param headerMap
     * @param httpClient
     * @return 参数  
     * @return String 返回类型
     */
    private static String commonHttpClientGet(String reqUrl, Map reqBodyParams, String encoding, Map headerMap, CloseableHttpClient httpClient) {
        String httpStr = null;  
        String reqParamStr = "";
        CloseableHttpResponse response = null;  
        try {  
           
            reqParamStr = reqParamStr(reqBodyParams, encoding, reqParamStr);
            
            HttpGet httpGet = null;
            if(ObjectUtil.isNotEmpty(reqParamStr)){
                System.out.println(reqUrl+"?"+reqParamStr);
                httpGet = new HttpGet(reqUrl+"?"+reqParamStr);  
            }else{
                httpGet = new HttpGet(reqUrl);  
            }
            /*设置请求头属性和值 */
            if(headerMap!=null && !headerMap.isEmpty()){
                 for (String key : headerMap.keySet()) {
                     Object value = headerMap.get(key);
                     //如: httpPost.addHeader("Content-Type", "application/json");  
                     httpGet.addHeader(key,String.valueOf(value));
                 }
            }
            httpGet.setConfig(requestConfig);  
            response = httpClient.execute(httpGet);  
            HttpEntity entity = response.getEntity();  
            if (entity != null && response.getStatusLine().getStatusCode()==200) {
                httpStr = EntityUtils.toString(entity,encoding);  
                logger.info(getCurrentClassName()+"#commonHttpClientGet,***reqUrl:***"+reqUrl+",Response content*** : " + httpStr);
            }else{
                httpStr = null;
                logger.error("httpClientGet的entity对象为空");
            }
        } catch (IOException e) {
            logger.error("HttpUrlPost出现异常,异常信息为:"+e.getMessage());
            e.printStackTrace();  
        } finally {  
            if (response != null) {  
                try {  
                    EntityUtils.consume(response.getEntity());  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }
        return httpStr;
    }
    
    
    public static String createHttpPost(String url, List params)  {
        try {
            CloseableHttpClient httpClient = createHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            
            if(httpResponse.getStatusLine()!=null && httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                String retMsg = EntityUtils.toString(httpResponse.getEntity(), DEFAULT_ENCODING);
                if(!ObjectUtil.isEmpty(retMsg)){
                    return retMsg;
                }
            }else{
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    public static String getCurrentClassName(){
        return HttpClientUtil.class.getName();
    }
    
}

  • SSLContextSecurity
/**
 * @Description SSLContextSecurity上下文安全處理類  
 * 
 * 
 * @ClassName   SSLContextSecurity  
 * @Date        2017年6月6日 上午10:45:09  
 * @Author      liangjilong  
 * @Copyright (c) All Rights Reserved, 2017.
 */
public class SSLContextSecurity {

    /** 
     * 绕过验证 
     *   
     * @return 
     * @throws NoSuchAlgorithmException  
     * @throws KeyManagementException  
     */  
    public static SSLSocketFactory createIgnoreVerifySSL(String sslVersion) throws NoSuchAlgorithmException, KeyManagementException {  
        //SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        SSLContext sc = SSLContext.getInstance(sslVersion); //"TLSv1.2"
        // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法  
        X509TrustManager trustManager = new X509TrustManager() {  
            @Override  
            public void checkClientTrusted(  
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,  
                    String paramString) throws CertificateException {  
            }  
            @Override  
            public void checkServerTrusted(  
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,  
                    String paramString) throws CertificateException {  
            }  
            @Override  
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
                return null;  
            }  
        };  
      
        sc.init(null, new TrustManager[] { trustManager }, new SecureRandom());  
        
        /***
         * 如果 hostname in certificate didn't match的话就给一个默认的主机验证
         */
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });  
        
        return  sc.getSocketFactory();
    }  
    
    /**
     * @Description 根据版本号进行获取协议项下  
     * @Author      liangjilong  
     * @Date        2017年6月6日 上午11:15:27  
     * @param tslVerision
     * @return 参数  
     * @return String[] 返回类型   
     * @throws
     */
    public static String[] getProtocols(String tslVerision){
        try {
            SSLContext context = SSLContext.getInstance(tslVerision);  
            context.init(null, null, null);  
            SSLSocketFactory factory = (SSLSocketFactory) context.getSocketFactory();  
            SSLSocket socket = (SSLSocket) factory.createSocket();  
            String [] protocols = socket.getSupportedProtocols();  
            for (int i = 0; i < protocols.length; i++) {  
                System.out.println(" " + protocols[i]);  
            }  
            return socket.getEnabledProtocols();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }  
        return null;
    }
 
}
  • IoUtils 工具类
    IoUtils 工具类

你可能感兴趣的:(Java的HttpClient封装http通信工具类)