1. 程式人生 > >HttpClient實現https請求

HttpClient實現https請求

package test.ssl;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.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.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.xylink.cms.common.util.UrlUtil;
public class SSLTest {
    private static Logger log = Logger.getLogger(SSLTest.class);
    static int TimeOutTime = 20000;
    final static String cacertFilePath = "/Users/hecj/server.jks";
    final static String cacertFilePassword = "xxx";
    @Test
    public void sslTest() {
        String params = "userName=xxx&password=xxx";
        try {
            sendPost("https://dev.hechaojie.com/doLogin", params, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * POST方式發起http請求
     */
    public static String sendPost(String url, String params, String charset) throws Exception {
        long time = System.currentTimeMillis();
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient httpClient = (CloseableHttpClient) getHttpClient();
        HttpContext httpContext = new BasicHttpContext();
        StringBuffer result = new StringBuffer();
        try {
            HttpPost post = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TimeOutTime)
                    .setConnectTimeout(TimeOutTime).build();// 設定請求和傳輸超時時間
            post.setConfig(requestConfig);
            log.info("執行post請求..." + post.getURI());
            // 建立引數列表
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            if (params != null) {
                Map<String, String> props = UrlUtil.url2map(params);
                for (String key : props.keySet()) {
                    nameValuePairs.add(new BasicNameValuePair(key, props.get(key)));
                }
            }
            // url格式編碼
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            post.setEntity(uefEntity);
            // 執行請求
            httpResponse = httpClient.execute(post, httpContext);
            HttpEntity entity = httpResponse.getEntity();
            if (null != entity) {
                result.append(new String(EntityUtils.toString(entity).getBytes("iso-8859-1"), "utf-8"));
            }
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                httpResponse.close();
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("http請求時間:" + (System.currentTimeMillis() - time) / 1000d + "s");
        }
        return result.toString();
    }
    /**
     * Create a httpClient instance
     */
    public static HttpClient getHttpClient() {
        CloseableHttpClient client = null;
        try {
            TrustManager[] tm = new TrustManager[] { new MyX509TrustManager(cacertFilePath, cacertFilePassword) };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, tm, new SecureRandom());
            client = HttpClients.custom().setSslcontext(sslContext)
                    .setHostnameVerifier(SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }
}
MyX509TrustManager.java程式碼
package test.ssl;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
    X509TrustManager myTrustManager;
    public MyX509TrustManager(String cacertFile, String password) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(cacertFile), password.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager trustManagers[] = trustManagerFactory.getTrustManagers();
        for(TrustManager trustManager : trustManagers) {
            if(trustManager instanceof X509TrustManager) {
                myTrustManager = (X509TrustManager) trustManager;
                return;
            }
        }
        throw new Exception("Couldn't initialize");
    }
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    }
    @Override
    public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
        if ((certificates != null) && (certificates.length == 1)) {
            certificates[0].checkValidity();
        } else {
            myTrustManager.checkServerTrusted(certificates, authType);
        }
    }
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return myTrustManager.getAcceptedIssuers();
    }