Java的HttpClient封裝http通信工具類

目的與初衷

最近在工作中需要在后臺調(diào)用第三方接口(微信雀彼,支付瓷蛙,華為點(diǎn)擊回?fù)埽ㄒ贿_(dá)物流快遞接口)伟件,最近在學(xué)習(xí)Kotlin硼啤,嘗試使用Kotlin和HttpClient,自己封裝了一個HttpClient工具類斧账,封裝常用實(shí)現(xiàn)get谴返,post工具方法類

1 什么是HttpClient

HTTP 協(xié)議可能是現(xiàn)在 Internet 上使用得最多、最重要的協(xié)議了咧织,越來越多的 Java 應(yīng)用程序需要直接通過 HTTP 協(xié)議來訪問網(wǎng)絡(luò)資源嗓袱。雖然在 JDK 的 java net包中已經(jīng)提供了訪問 HTTP 協(xié)議的基本功能,但是對于大部分應(yīng)用程序來說习绢,JDK 庫本身提供的功能還不夠豐富和靈活渠抹。HttpClient 是Apache HttpComponents 下的子項(xiàng)目,用來提供高效的闪萄、最新的梧却、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議败去。

2 功能介紹

  • 支持自動轉(zhuǎn)向
  • 支持 HTTPS 協(xié)議
  • 支持代理服務(wù)器等

3. 版本比較

注意本篇博客主要是基于 HttpClient4.5.5 版本的來講解的放航,也是現(xiàn)在最新的版本,之所以要提供版本說明的是因?yàn)?HttpClient 3 版本和 HttpClient 4 版本差別還是很多大的圆裕,基本HttpClient里面的接口都變了广鳍,你把 HttpClient 3 版本的代碼拿到 HttpClient 4 上面都運(yùn)行不起來缺菌,會報(bào)錯的。所以一定要注意 HtppClient 的版本問題搜锰。

4. HttpClient不能做的事情

HttpClient 不是瀏覽器伴郁,它是一個客戶端 HTTP 協(xié)議傳輸類庫。HttpClient 被用來發(fā)送和接受 HTTP 消息蛋叼。HttpClient 不會處理 HTTP 消息的內(nèi)容焊傅,不會進(jìn)行 javascript 解析武福,不會關(guān)心 content type趋观,如果沒有明確設(shè)置,HttpClient 也不會對請求進(jìn)行格式化巷查、重定向 url歌馍,或者其他任何和 HTTP 消息傳輸相關(guān)的功能握巢。

5. HttpClient使用流程

使用HttpClient發(fā)送請求、接收響應(yīng)很簡單松却,一般需要如下幾步即可暴浦。

    1. 創(chuàng)建HttpClient對象。
    1. 創(chuàng)建請求方法的實(shí)例晓锻,并指定請求URL歌焦。如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象砚哆;如果需要發(fā)送POST請求独撇,創(chuàng)建HttpPost對象。
    1. 如果需要發(fā)送請求參數(shù)躁锁,可調(diào)用HttpGetsetParams方法來添加請求參數(shù)纷铣;對于HttpPost對象而言,可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)战转。
    1. 調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求搜立,該方法返回一個HttpResponse對象。
    1. 調(diào)用HttpResponse的getAllHeaders()匣吊、getHeaders(String name)等方法可獲取服務(wù)器的響應(yīng)頭儒拂;調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容色鸳。程序可通過該對象獲取服務(wù)器的響應(yīng)內(nèi)容。
    1. 釋放連接见转。無論執(zhí)行方法是否成功命雀,都必須釋放連接

6、 HttpClient與Java結(jié)合使用


/**
 * @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");//換行相當(dāng)于\n

    static {  
        // 設(shè)置連接池  
        connMgr = new PoolingHttpClientConnectionManager();  
        // 設(shè)置連接池大小  
        connMgr.setMaxTotal(100);  
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());  

        RequestConfig.Builder configBuilder = RequestConfig.custom();  
        // 設(shè)置連接超時(shí)  
        configBuilder.setConnectTimeout(MAX_TIMEOUT);  
        // 設(shè)置讀取超時(shí)  
        configBuilder.setSocketTimeout(MAX_TIMEOUT);  
        // 設(shè)置從連接池獲取連接實(shí)例的超時(shí)  
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);  
        // 在提交請求之前 測試連接是否可用  
        configBuilder.setStaleConnectionCheckEnabled(true);  
        requestConfig = configBuilder.build();  
    }

    /**
     * @Description get請求鏈接  
     * @Date        2017年6月6日 上午11:36:09  
     * @param rURL
     * @return 參數(shù)  
     * @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);//將讀超時(shí)設(shè)置為指定的超時(shí)斩箫,以毫秒為單位吏砂。用一個非零值指定在建立到資源的連接后從 Input 流讀入時(shí)的超時(shí)時(shí)間撵儿。如果在數(shù)據(jù)可讀取之前超時(shí)期滿,則會引發(fā)一個 java.net.SocketTimeoutException狐血。
            con.setDoInput(true);//指示應(yīng)用程序要從 URL 連接讀取數(shù)據(jù)淀歇。
            con.setRequestMethod("GET");//設(shè)置請求方式
            if(con.getResponseCode() == 200){//當(dāng)請求成功時(shí),接收數(shù)據(jù)(狀態(tài)碼“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 參數(shù)  
     * @return String 返回類型   
     * @throws
     */
    public static String post(String postUrl, Map<String, Object> 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 獲取參數(shù)內(nèi)容   
     * @Date        2017年6月6日 上午11:36:50  
     * @throws UnsupportedEncodingException 參數(shù)  
     * @return String 返回類型   
     * @throws
     */
    public static String getConcatParams(Map<String, Object> params) throws UnsupportedEncodingException {
        String content = null;
        Set<Entry<String,Object>> set = params.entrySet();//Map.entrySet 方法返回映射的 collection 視圖匈织,其中的元素屬于此類
        StringBuilder sb = new StringBuilder();
        for(Entry<String,Object> i: set){
            //將參數(shù)解析為"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 拼接請求參數(shù)  
     * @Date        2017年5月24日 上午10:39:28  
     * @param @return 參數(shù)  
     * @return String 返回結(jié)果如:  userName=1111&passWord=222  
     * @throws
     */
    private static String getContent(Map<String, Object> params, String encoding) throws UnsupportedEncodingException {
        String content = null;
        Set<Entry<String,Object>> set = params.entrySet();//Map.entrySet 方法返回映射的 collection 視圖浪默,其中的元素屬于此類
        StringBuilder sb = new StringBuilder();
        for(Entry<String,Object> i: set){
            //將參數(shù)解析為"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<String, Object> 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);//將讀超時(shí)設(shè)置為指定的超時(shí),以毫秒為單位缀匕。用一個非零值指定在建立到資源的連接后從 Input 流讀入時(shí)的超時(shí)時(shí)間纳决。如果在數(shù)據(jù)可讀取之前超時(shí)期滿,則會引發(fā)一個 java.net.SocketTimeoutException乡小。
            con.setDoInput(true);//指示應(yīng)用程序要從 URL 連接讀取數(shù)據(jù)阔加。
            con.setRequestMethod("GET");//設(shè)置請求方式
            if(con.getResponseCode() == 200){//當(dāng)請求成功時(shí),接收數(shù)據(jù)(狀態(tài)碼“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 參數(shù)  
     * @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 參數(shù)  
     * @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+"返回的數(shù)據(jù)為"+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 當(dāng)isSSL=true的時(shí)候支持Https處理胜榔,當(dāng)isSSL=false的時(shí)候http請求
     * @param sslVersion  支持https的版本參數(shù)
     * @return 參數(shù)  
     * @return String 返回類型   
     * @throws
     */
    public static String createHttps(String requestUrl, String requestMethod,Map<String,Object> 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){
                //這行代碼必須要在創(chuàng)建URL對象之前,因?yàn)橄刃r?yàn)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);//是否支持緩存

            /*設(shè)置請求頭屬性和值 */
            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));
                 }
            }

            // 設(shè)置請求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            // 當(dāng)設(shè)置body請求參數(shù)
            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){
                // 從輸入流讀取返回內(nèi)容
                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("連接超時(shí):{}",  ce+"\t請求鏈接"+requestUrl);
        } catch (Exception e) {
            logger.error("https請求異常:{}", e+"\t請求鏈接"+requestUrl);
            return "FAIL";//請求系統(tǒng)頻繁
        }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 "";
    }

     /** 
     * 發(fā)送 POST 請求(HTTP)湃番,JSON形式 
     * @Author      liangjilong  
     * @Date        2017年5月22日 下午3:57:03  
     * @param @param apiUrl
     * @param @param json
     * @param @param contentType
     * @param @return 參數(shù)  
     * @return String 返回類型   
     * @throws
     */
    public static String httpClientPost(String reqUrl, Object reqBodyParams,String contentType,String encoding,Map<String,Object> headerMap) {  
        String  result ="";  
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        HttpPost httpPost = new HttpPost(reqUrl);  

        /*設(shè)置請求頭屬性和值 */
        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方法返回的參數(shù)為:"+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,因?yàn)镋ntityUtils.toString(HttpEntity)方法被使用了多次苗分。所以每個方法內(nèi)只能使用一次。
                //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出現(xiàn)異常牵辣,異常信息為:"+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  發(fā)送 POST 請求(HTTP)摔癣,JSON形式   
    * @Author      liangjilong 
    * @throws
    */
   public static String httpClientPost(String reqUrl, Map<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> 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<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> 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 參數(shù)  
     * @return String 返回類型
     */
    private static String reqParamStr(Map<String, Object> reqBodyParams, String encoding, String reqParamStr) throws IOException,
            UnsupportedEncodingException {
        if(reqBodyParams!=null && !reqBodyParams.isEmpty()){
            //封裝請求參數(shù)  
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> 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 創(chuàng)建httpClient  
     * @Date        2017年8月1日 上午10:26:29  
     * @return 參數(shù)  
     * @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 創(chuàng)建httpsPost  
     * @Date        2017年8月1日 上午10:29:09  
     * @param reqUrl
     * @param reqBodyParams
     * @param contentType
     * @param encoding
     * @param headerMap
     * @return 參數(shù)  
     * @return String 返回類型
     */
    public static String createHttpsPost(String reqUrl, Map<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> 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 參數(shù)  
     * @return String 返回類型
     */
    private static String commonHttpClientPost(String reqUrl, Map<String, Object> reqBodyParams, String contentType, String encoding, Map<String, Object> headerMap, CloseableHttpClient httpClient) {
        String  result ="";  
        CloseableHttpResponse response = null;  
    try {  
         HttpPost httpPost = new HttpPost(reqUrl);  
         String reqParamStr = "";
         /*設(shè)置請求頭屬性和值 */
         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出現(xiàn)異常,異常信息為:"+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<String,Object> reqBodyParams,String contentType,String encoding,Map<String,Object> 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 參數(shù)  
     * @return String 返回類型
     */
    private static String commonHttpClientGet(String reqUrl, Map<String, Object> reqBodyParams, String encoding, Map<String, Object> 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);  
            }
            /*設(shè)置請求頭屬性和值 */
            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出現(xiàn)異常纬向,異常信息為:"+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<BasicNameValuePair> 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 {

    /** 
     * 繞過驗(yàn)證 
     *   
     * @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"
        // 實(shí)現(xiàn)一個X509TrustManager接口择浊,用于繞過驗(yàn)證,不用修改里面的方法  
        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的話就給一個默認(rèn)的主機(jī)驗(yàn)證
         */
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });  

        return  sc.getSocketFactory();
    }  

    /**
     * @Description 根據(jù)版本號進(jìn)行獲取協(xié)議項(xiàng)下  
     * @Author      liangjilong  
     * @Date        2017年6月6日 上午11:15:27  
     * @param tslVerision
     * @return 參數(shù)  
     * @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;
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末逾条,一起剝皮案震驚了整個濱河市琢岩,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌师脂,老刑警劉巖担孔,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異吃警,居然都是意外死亡糕篇,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進(jìn)店門酌心,熙熙樓的掌柜王于貴愁眉苦臉地迎上來拌消,“玉大人,你說我怎么就攤上這事安券《毡溃” “怎么了氓英?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長鹦筹。 經(jīng)常有香客問我铝阐,道長,這世上最難降的妖魔是什么铐拐? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任徘键,我火速辦了婚禮,結(jié)果婚禮上余舶,老公的妹妹穿的比我還像新娘啊鸭。我一直安慰自己,他們只是感情好匿值,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布赠制。 她就那樣靜靜地躺著,像睡著了一般挟憔。 火紅的嫁衣襯著肌膚如雪钟些。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天绊谭,我揣著相機(jī)與錄音政恍,去河邊找鬼。 笑死达传,一個胖子當(dāng)著我的面吹牛篙耗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播宪赶,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼宗弯,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了搂妻?” 一聲冷哼從身側(cè)響起蒙保,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎欲主,沒想到半個月后邓厕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡扁瓢,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年详恼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片涤妒。...
    茶點(diǎn)故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡单雾,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出她紫,到底是詐尸還是另有隱情硅堆,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布贿讹,位于F島的核電站渐逃,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏民褂。R本人自食惡果不足惜茄菊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望赊堪。 院中可真熱鬧面殖,春花似錦、人聲如沸哭廉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽遵绰。三九已至辽幌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間椿访,已是汗流浹背乌企。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留成玫,地道東北人加酵。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像哭当,于是被迫代替她去往敵國和親猪腕。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 目的與初衷 最近在工作中需要在后臺調(diào)用第三方接口(微信荣病,支付码撰,華為點(diǎn)擊回?fù)埽ㄒ贿_(dá)物流快遞接口)个盆,最近在學(xué)習(xí)Ko...
    愛學(xué)習(xí)的蹭蹭閱讀 2,601評論 0 7
  • 前言 超文本傳輸協(xié)議(HTTP)也許是當(dāng)今互聯(lián)網(wǎng)上使用的最重要的協(xié)議了脖岛。Web服務(wù),有網(wǎng)絡(luò)功能的設(shè)備和網(wǎng)絡(luò)計(jì)算的發(fā)...
    狂奔的蝸牛_wxc閱讀 5,511評論 0 12
  • 目的與初衷 最近在工作中需要在后臺調(diào)用第三方接口(微信颊亮,支付柴梆,華為點(diǎn)擊回?fù)埽ㄒ贿_(dá)物流快遞接口)终惑,最近在學(xué)習(xí)Ko...
    愛學(xué)習(xí)的蹭蹭閱讀 3,106評論 0 1
  • 目的與初衷 最近在工作中需要在后臺調(diào)用第三方接口(微信绍在,支付,華為點(diǎn)擊回?fù)埽ㄒ贿_(dá)物流快遞接口)偿渡,最近在學(xué)習(xí)Ko...
    zwb_jianshu閱讀 970評論 0 0
  • 1 于琛在四月的尾巴玩了個溫暖的游戲臼寄,“只要你點(diǎn)贊,我就告訴你一個關(guān)于你和我的回憶溜宽〖” 然后就開啟了下午至深夜一長...
    老驢三兒閱讀 362評論 0 1