1. 程式人生 > >HttpsUtils 支援http和https請求

HttpsUtils 支援http和https請求

package com.foresee.zxpt.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * https請求工具類
 * 
 * @author GZ
 *
 */
public class HttpsUtils {

	protected static Log logger = LogFactory.getLog(HttpsUtils.class);
	/**
	 * post請求 支援https 有證書和無證書
	 * @param url  請求url
	 * @param postData  post表單
	 * @param header  請求頭
	 * @param encoding  編碼
	 * @param connectionTimeout 請求超時時間
	 * @param socketTimeout 傳輸超時時間
	 * @param isNoSSL  是否不帶證書
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String doPostByClient(String url, Map<?, ?> postData, Map<?, ?> header, String encoding,
			long connectionTimeout, long socketTimeout, boolean isNoSSL)  {
		CloseableHttpClient client=null;
		try {
			client = HttpClients.createDefault();
			if (isNoSSL) {
				client = (CloseableHttpClient) wrapClient(client);
			}

			HttpPost httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) socketTimeout)
					.setConnectTimeout((int) connectionTimeout).build();// 設定請求和傳輸超時時
			httpPost.setConfig(requestConfig);

			// 頭部請求資訊
			if (header != null) {
				Set<?> entrySet = header.entrySet();
				for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
					Map.Entry entry = (Map.Entry) itor.next();
					httpPost.addHeader(entry.getKey().toString(), entry.getValue().toString());
				}
			}

			List<NameValuePair> parameters = new ArrayList<NameValuePair>();

			if (postData != null) {

				Set<?> entrySet = postData.entrySet();

				for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {

					Map.Entry entry = (Map.Entry) itor.next();

					parameters.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() + ""));

				}

				// 建立UrlEncodedFormEntity物件
				UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, encoding);

				httpPost.setEntity(formEntiry);
			}

			// 執行請求

			CloseableHttpResponse response = client.execute(httpPost);
			if(response.getStatusLine().getStatusCode()==200){
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String result = EntityUtils.toString(entity);
					response.close();
					return result;
				}
			}
		} catch (ConnectTimeoutException  e) {
			logger.error(e.getMessage());
//			throw new UnsupportedEncodingException(e.getMessage());
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
//			throw new UnsupportedEncodingException(e.getMessage());
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage());
//			throw new UnsupportedEncodingException(e.getMessage());
		} catch (ParseException e) {
			logger.error(e.getMessage());
//			throw new UnsupportedEncodingException(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
//			throw new UnsupportedEncodingException(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
//			throw new UnsupportedEncodingException(e.getMessage());
		}finally{
			if(client!=null){
				// 關閉HttpClient
				client.getConnectionManager().shutdown();
			}
		}
		return "";
	}

	/**
	 * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”異常
	 * 不用匯入SSL證書
	 * 
	 * @param base
	 * @return
	 */
	public static HttpClient wrapClient(HttpClient base) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
			ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
	            @Override
	            public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
	                return 20 * 1000; // tomcat預設keepAliveTimeout為20s
	            }
	        };
	        
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).setKeepAliveStrategy(connectionKeepAliveStrategy).build();
			return httpclient;
		} catch (Exception ex) {
			logger.error(ex.getLocalizedMessage());
			return HttpClients.createDefault();
		}
	}
}
x 180   1
package
com.foresee.zxpt.common.utils;
2
3
import java.io.IOException;
4
import
java.io.UnsupportedEncodingException;
5
import java.security.cert.CertificateException;
6
import java.security.cert.X509Certificate;
7
import java.util.ArrayList;
8
import java.util.Iterator;
9
import java.util.List;
10
import java.util.Map;
11
import java.util.Set;
12
13
import javax.net.ssl.SSLContext;
14
import javax.net.ssl.TrustManager;
15
import javax.net.ssl.X509TrustManager;
16
17
import org.apache.commons.logging.Log;
18
import org.apache.commons.logging.LogFactory;
19
import org.apache.http.HttpEntity;
20
import org.apache.http.HttpResponse;
21
import org.apache.http.NameValuePair;
22
import org.apache.http.ParseException;
23
import org.apache.http.client.ClientProtocolException;
24
import org.apache.http.client.HttpClient;
25
import org.apache.http.client.config.RequestConfig;
26
import org.apache.http.client.entity.UrlEncodedFormEntity;
27
import org.apache.http.client.methods.CloseableHttpResponse;
28
import org.apache.http.client.methods.HttpPost;
29
import org.apache.http.conn.ConnectTimeoutException;
30
import org.apache.http.conn.ConnectionKeepAliveStrategy;
31
import org.apache.http.conn.ssl.NoopHostnameVerifier;
32
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
33
import org.apache.http.impl.client.CloseableHttpClient;
34
import org.apache.http.impl.client.HttpClients;
35
import org.apache.http.message.BasicNameValuePair;
36
import org.apache.http.protocol.HttpContext;
37
import org.apache.http.util.EntityUtils;
38
39
/**
40
 * https請求工具類
41
 * 
42
 * @author GZ
43
 *
44
 */
45
public class HttpsUtils {
46
47
    protected static Log logger = LogFactory.getLog(HttpsUtils.class);
48
    /**
49
     * post請求 支援https 有證書和無證書
50
     * @param url  請求url
51
     * @param postData  post表單
52
     * @param header  請求頭
53
     * @param encoding  編碼
54
     * @param connectionTimeout 請求超時時間
55
     * @param socketTimeout 傳輸超時時間
56
     * @param isNoSSL  是否不帶證書
57
     * @return
58
     * @throws UnsupportedEncodingException 
59
     * @throws Exception
60
     */
61
    @SuppressWarnings("deprecation")
62
    public static String doPostByClient(String url, Map<?, ?> postData, Map<?, ?> header, String encoding,
63
            long connectionTimeout, long socketTimeout, boolean isNoSSL)  {
64
        CloseableHttpClient client=null;
65
        try {
66
            client = HttpClients.createDefault();
67
            if (isNoSSL) {
68
                client = (CloseableHttpClient) wrapClient(client);
69
            }
70
71
            HttpPost httpPost = new HttpPost(url);
72
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) socketTimeout)
73
                    .setConnectTimeout((int) connectionTimeout).build();// 設定請求和傳輸超時時
74
            httpPost.setConfig(requestConfig);
75
76
            // 頭部請求資訊
77
            if (header != null) {
78
                Set<?> entrySet = header.entrySet();
79
                for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
80
                    Map.Entry entry = (Map.Entry) itor.next();
81
                    httpPost.addHeader(entry.getKey().toString(), entry.getValue().toString());
82
                }
83
            }
84
85
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
86
87
            if (postData != null) {
88
89
                Set<?> entrySet = postData.entrySet();
90
91
                for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
92
93
                    Map.Entry entry = (Map.Entry) itor.next();
94
95
                    parameters.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() + ""));
96
97
                }
98
99
                // 建立UrlEncodedFormEntity物件
100
                UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, encoding);
101
102
                httpPost.setEntity(formEntiry);
103
            }
104
105
            // 執行請求
106
107
            CloseableHttpResponse response = client.execute(httpPost);
108
            if(response.getStatusLine().getStatusCode()==200){
109
                HttpEntity entity = response.getEntity