Java的HttpClient封裝http通信工具類

目的與初衷

最近在工作中需要在后臺(tái)調(diào)用第三方接口(微信,支付,華為點(diǎn)擊回?fù)茇韵郏ㄒ贿_(dá)物流快遞接口),最近在學(xué)習(xí)Kotlin麦到,嘗試使用Kotlin和HttpClient绿饵,自己封裝了一個(gè)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 功能介紹

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

3. 版本比較

注意本篇博客主要是基于 HttpClient4.5.5 版本的來講解的,也是現(xiàn)在最新的版本疮装,之所以要提供版本說明的是因?yàn)?HttpClient 3 版本和 HttpClient 4 版本差別還是很多大的缘琅,基本HttpClient里面的接口都變了粘都,你把 HttpClient 3 版本的代碼拿到 HttpClient 4 上面都運(yùn)行不起來廓推,會(huì)報(bào)錯(cuò)的。所以一定要注意 HtppClient 的版本問題翩隧。

4. HttpClient不能做的事情

HttpClient 不是瀏覽器樊展,它是一個(gè)客戶端 HTTP 協(xié)議傳輸類庫。HttpClient 被用來發(fā)送和接受 HTTP 消息堆生。HttpClient 不會(huì)處理 HTTP 消息的內(nèi)容专缠,不會(huì)進(jìn)行 javascript 解析,不會(huì)關(guān)心 content type淑仆,如果沒有明確設(shè)置涝婉,HttpClient 也不會(huì)對請求進(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ā)送請求珊燎,該方法返回一個(gè)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í)捌蚊,以毫秒為單位。用一個(gè)非零值指定在建立到資源的連接后從 Input 流讀入時(shí)的超時(shí)時(shí)間近弟。如果在數(shù)據(jù)可讀取之前超時(shí)期滿缅糟,則會(huì)引發(fā)一個(gè) 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í)赴涵,以毫秒為單位。用一個(gè)非零值指定在建立到資源的連接后從 Input 流讀入時(shí)的超時(shí)時(shí)間订讼。如果在數(shù)據(jù)可讀取之前超時(shí)期滿髓窜,則會(huì)引發(fā)一個(gè) 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)方法被使用了多次帆阳。所以每個(gè)方法內(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)一個(gè)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的話就給一個(gè)默認(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)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市阶祭,隨后出現(xiàn)的幾起案子绷杜,更是在濱河造成了極大的恐慌直秆,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鞭盟,死亡現(xiàn)場離奇詭異圾结,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)齿诉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門筝野,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人粤剧,你說我怎么就攤上這事歇竟。” “怎么了抵恋?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵焕议,是天一觀的道長。 經(jīng)常有香客問我馋记,道長号坡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任梯醒,我火速辦了婚禮,結(jié)果婚禮上腌紧,老公的妹妹穿的比我還像新娘茸习。我一直安慰自己,他們只是感情好壁肋,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布号胚。 她就那樣靜靜地躺著,像睡著了一般浸遗。 火紅的嫁衣襯著肌膚如雪猫胁。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天跛锌,我揣著相機(jī)與錄音弃秆,去河邊找鬼。 笑死髓帽,一個(gè)胖子當(dāng)著我的面吹牛菠赚,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播郑藏,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼衡查,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了必盖?” 一聲冷哼從身側(cè)響起拌牲,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤俱饿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后塌忽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體稍途,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年砚婆,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了械拍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡装盯,死狀恐怖坷虑,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情埂奈,我是刑警寧澤迄损,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站账磺,受9級特大地震影響芹敌,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜垮抗,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一氏捞、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧冒版,春花似錦液茎、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至续室,卻和暖如春栋烤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背挺狰。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工明郭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人她渴。 一個(gè)月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓达址,卻偏偏與公主長得像,于是被迫代替她去往敵國和親趁耗。 傳聞我的和親對象是個(gè)殘疾皇子沉唠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評論 2 354

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

  • 目的與初衷 最近在工作中需要在后臺(tái)調(diào)用第三方接口(微信,支付苛败,華為點(diǎn)擊回?fù)苈穑ㄒ贿_(dá)物流快遞接口)径簿,最近在學(xué)習(xí)Ko...
    愛學(xué)習(xí)的蹭蹭閱讀 3,110評論 0 1
  • 1.1 請求執(zhí)行 HttpClient 最重要的功能是執(zhí)行 HTTP 方法。執(zhí)行 HTTP 方法涉及一個(gè)或多個(gè) H...
    changhr2013閱讀 6,043評論 1 7
  • 前言 超文本傳輸協(xié)議(HTTP)也許是當(dāng)今互聯(lián)網(wǎng)上使用的最重要的協(xié)議了嘀韧。Web服務(wù)篇亭,有網(wǎng)絡(luò)功能的設(shè)備和網(wǎng)絡(luò)計(jì)算的發(fā)...
    狂奔的蝸牛_wxc閱讀 5,514評論 0 12
  • 由于簡書2019年9月不可以發(fā)布新的博客,已經(jīng)把最新的博客發(fā)布到CSDN了锄贷,文章鏈接HttpClient工具類
    JourWon閱讀 54,152評論 9 81
  • 我國酒吧行業(yè)總體經(jīng)營情況 伴隨著中國整體經(jīng)濟(jì)的發(fā)展译蒂,中國酒吧從起步階段進(jìn)入了快速發(fā)展期。全國酒吧數(shù)量接近3萬家谊却。在...
    樂享音樂平臺(tái)閱讀 176評論 0 0