1. 程式人生 > >HttpClient實現的https工具類

HttpClient實現的https工具類

以下工具類所用到httpClient4.5.jar和log4j.jar
import java.io.IOException;
import java.net.URLDecoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpRequestUtils {
    private static Logger logger = Logger.getLogger(HttpRequestUtils.class);    //日誌記錄
 
    private static CloseableHttpClient getHttpClient() {  
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();  
        ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();  
        registryBuilder.register("http", plainSF);  
//指定信任金鑰儲存物件和連線套接字工廠  
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
            //信任任何連結  
            TrustStrategy anyTrustStrategy = new TrustStrategy() {

				public boolean isTrusted(X509Certificate[] arg0, String arg1)
						throws CertificateException {
					return true;
				}   
            };  
            SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();  
            LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
            registryBuilder.register("https", sslSF);  
        } catch (KeyStoreException e) {  
            throw new RuntimeException(e);  
        } catch (KeyManagementException e) {  
            throw new RuntimeException(e);  
        } catch (NoSuchAlgorithmException e) {  
            throw new RuntimeException(e);  
        }  
        Registry<ConnectionSocketFactory> registry = registryBuilder.build();  
        //設定連線管理器  
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);  
//      connManager.setDefaultConnectionConfig(connConfig);  
//      connManager.setDefaultSocketConfig(socketConfig);  
        //構建客戶端  
        return HttpClientBuilder.create().setConnectionManager(connManager).build();  
    }  
    
  
    public static String httpPost(String param,String url,Map<String, String> httpHead) throws Exception{
    	
        CloseableHttpClient httpclient = getHttpClient();
		String result = null;
    	try {
    		HttpPost request = new HttpPost(url);
    		 //解決中文亂碼問題
            StringEntity entity = new StringEntity(param, "utf-8");
            
            request.setEntity(entity);
    		
            //設定http頭引數
            if(httpHead!=null&&httpHead.size()>0)
            for(Iterator<Entry<String, String>> ies = httpHead.entrySet().iterator(); ies.hasNext();){
                	Entry<String, String> entry = ies.next();
                	
                	String key =entry.getKey();
                	String value = entry.getValue();
                	
                	request.addHeader(key, value);
             }
                
    		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();//設定請求和傳輸超時時間
    		request.setConfig(requestConfig);
            CloseableHttpResponse response = httpclient.execute(request);
            url = URLDecoder.decode(url, "UTF-8");
            
            logger.info("請求介面:"+url+",執行狀態:"+response.getStatusLine().getStatusCode());
            
            /**請求傳送成功,並得到響應**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    /**讀取伺服器返回過來的字串資料**/
                	result = EntityUtils.toString(response.getEntity(),"UTF-8");
                	//System.out.println("result:"+result);
                } catch (Exception e) {
                    logger.error("post請求提交失敗:" + url, e);
                } finally {
                	response.close();
                }
            } else {
            	result = response.getStatusLine().getStatusCode()+"-"+response.getStatusLine().getReasonPhrase();

            }
		} catch (Exception e) {
            logger.error("post請求提交失敗:" + url, e);
		}finally{
			httpclient.close();
		}
    	return result;
    }
    
    public static String httpGet(String url ,Map<String ,String > httpHeader) throws IOException{
        //get請求返回結果
        CloseableHttpClient httpclient = getHttpClient();
        String strResult = null;  
        try {
        	//傳送get請求
            HttpGet request = new HttpGet(url);
            
            //設定http頭引數
            if(httpHeader!=null && httpHeader.size()>0){
	            for(Iterator<Entry<String, String>> ies = httpHeader.entrySet().iterator(); ies.hasNext();){
	                Entry<String, String> entry = ies.next();
	                String key =entry.getKey();
	                String value = entry.getValue();
	                request.addHeader(key, value);
	             }
            }
            CloseableHttpResponse response = httpclient.execute(request);
                 
            /**請求傳送成功,並得到響應**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            	try {
            		/**讀取伺服器返回過來的json字串資料**/
            		strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
                    url = URLDecoder.decode(url, "UTF-8");
            	}catch(Exception e) {
            		logger.error("get請求提交失敗:" + url);
            	}finally {
            		 response.close();
            	}
            }
            
        } catch (IOException e) {
            logger.error("get請求提交失敗:" + url, e);
        } finally {
        	httpclient.close();
        }
        return strResult;
    }
    
}
借鑑的文章:http://blog.csdn.net/shenyunsese/article/details/41075579