Java的HttpClient封裝http通信工具類

目的與初衷

最近在工作中需要在后臺調用第三方接口(微信,支付,華為點擊回撥,三通一達物流快遞接口),最近在學習Kotlin,嘗試使用Kotlin和HttpClient,自己封裝了一個HttpClient工具類,封裝常用實現(xiàn)get,post工具方法類

1 什么是HttpClient

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

2 功能介紹

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

3. 版本比較

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

4. HttpClient不能做的事情

HttpClient 不是瀏覽器,它是一個客戶端 HTTP 協(xié)議傳輸類庫。HttpClient 被用來發(fā)送和接受 HTTP 消息。HttpClient 不會處理 HTTP 消息的內容,不會進行 javascript 解析,不會關心 content type,如果沒有明確設置,HttpClient 也不會對請求進行格式化、重定向 url,或者其他任何和 HTTP 消息傳輸相關的功能。

5. HttpClient使用流程

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

    1. 創(chuàng)建HttpClient對象。
    1. 創(chuàng)建請求方法的實例,并指定請求URL。如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象;如果需要發(fā)送POST請求,創(chuàng)建HttpPost對象。
    1. 如果需要發(fā)送請求參數(shù),可調用HttpGetsetParams方法來添加請求參數(shù);對于HttpPost對象而言,可調用setEntity(HttpEntity entity)方法來設置請求參數(shù)。
    1. 調用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求,該方法返回一個HttpResponse對象。
    1. 調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。
    1. 釋放連接。無論執(zhí)行方法是否成功,都必須釋放連接

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 參數(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);//將讀超時設置為指定的超時,以毫秒為單位。用一個非零值指定在建立到資源的連接后從 Input 流讀入時的超時時間。如果在數(shù)據(jù)可讀取之前超時期滿,則會引發(fā)一個 java.net.SocketTimeoutException。
            con.setDoInput(true);//指示應用程序要從 URL 連接讀取數(shù)據(jù)。
            con.setRequestMethod("GET");//設置請求方式
            if(con.getResponseCode() == 200){//當請求成功時,接收數(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ù)內容   
     * @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 返回結果如:  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);//將讀超時設置為指定的超時,以毫秒為單位。用一個非零值指定在建立到資源的連接后從 Input 流讀入時的超時時間。如果在數(shù)據(jù)可讀取之前超時期滿,則會引發(fā)一個 java.net.SocketTimeoutException。
            con.setDoInput(true);//指示應用程序要從 URL 連接讀取數(shù)據(jù)。
            con.setRequestMethod("GET");//設置請求方式
            if(con.getResponseCode() == 200){//當請求成功時,接收數(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 當isSSL=true的時候支持Https處理,當isSSL=false的時候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對象之前,因為先校驗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請求參數(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){
                // 從輸入流讀取返回內容
                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";//請求系統(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);  
        
        /*設置請求頭屬性和值 */
        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,因為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出現(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 = "";
         /*設置請求頭屬性和值 */
         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);  
            }
            /*設置請求頭屬性和值 */
            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 {

    /** 
     * 繞過驗證 
     *   
     * @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"
        // 實現(xiàn)一個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 根據(jù)版本號進行獲取協(xié)議項下  
     * @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;
    }
 
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 目的與初衷 最近在工作中需要在后臺調用第三方接口(微信,支付,華為點擊回撥,三通一達物流快遞接口),最近在學習Ko...
    愛學習的蹭蹭閱讀 3,465評論 0 1
  • 1.1 請求執(zhí)行 HttpClient 最重要的功能是執(zhí)行 HTTP 方法。執(zhí)行 HTTP 方法涉及一個或多個 H...
    changhr2013閱讀 6,195評論 1 7
  • 前言 超文本傳輸協(xié)議(HTTP)也許是當今互聯(lián)網上使用的最重要的協(xié)議了。Web服務,有網絡功能的設備和網絡計算的發(fā)...
    狂奔的蝸牛_wxc閱讀 5,650評論 0 12
  • 由于簡書2019年9月不可以發(fā)布新的博客,已經把最新的博客發(fā)布到CSDN了,文章鏈接HttpClient工具類
    JourWon閱讀 54,332評論 9 81
  • 我國酒吧行業(yè)總體經營情況 伴隨著中國整體經濟的發(fā)展,中國酒吧從起步階段進入了快速發(fā)展期。全國酒吧數(shù)量接近3萬家。在...
    樂享音樂平臺閱讀 224評論 0 0

友情鏈接更多精彩內容