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 nameValuePairs = new ArrayList();
            if (params != null) {
                Map 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();
    }

你可能感兴趣的:(java)