HttpsClient.java 6.87 KB
package com.cjs.cms.util.net;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.web.util.UriTemplate;

public class HttpsClient {

    private static final String        HTTPS_URL                = "https://192.168.10.186/pub/login";
    private static final String        KEY_STORE_TRUST_PASSWORD = "123456";
    private static final String        CLIENT_KEY_PASS          = "123456";

    private static CloseableHttpClient httpClient               = null;
    private static RequestConfig       requestConfig            = null;
    private static final int           TIME_OUT                 = 5000;

    public static final Charset        CHARSET                  = Charset.forName("UTF-8");          // httpclient读取内容时使用的字符集

    public static void main(String[] args) throws Exception {
        System.out.println(doGet(HTTPS_URL, new HashMap<String, String>()));
    }

    static {
        try {
            String path = HttpsClient.class.getResource("/ssl2/").getFile();

            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(new FileInputStream(new File(path + "/client.p12")),
                KEY_STORE_TRUST_PASSWORD.toCharArray());
            SSLContext sslcontext = SSLContexts.custom()
                //忽略掉对服务器端证书的校验
                .loadTrustMaterial(new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain,
                                             String authType) throws CertificateException {
                        return true;
                    }
                })
                //加载服务端提供的truststore(如果服务器提供truststore的话就不用忽略对服务器端证书的校验了)
                //.loadTrustMaterial(new File("D:\\truststore.jks"), "123456".toCharArray(),
                //        new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore, CLIENT_KEY_PASS.toCharArray()).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
                .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
    * POST请求
    * @param uri 请求的URI
    * @param params 请求参数
    * @return 远程服务器相应,如果状态不是200,则返回null
    */
    public static String doPost(String uri, Map<String, String> params) throws Exception {
        HttpPost httpPost = new HttpPost(uri);
        CloseableHttpResponse response = null;
        try {
            httpPost.setConfig(requestConfig);
            //绑定到请求 Entry
            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                formParams.add(new BasicNameValuePair(key, params.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, CHARSET));
            response = httpClient.execute(httpPost);
            if (response == null || response.getStatusLine().getStatusCode() != 200) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            //使用EntityUtils的toString方法,传递编码,默认编码是ISO-8859-1
            return EntityUtils.toString(entity, getContentCharSet(entity));
        } catch (Exception e) {
            throw e;
        } finally {
            if (response != null) {
                response.close();
            }
            httpPost.releaseConnection();
        }

    }

    /**获取响应的编码类型,默认为UTF-8*/
    private static String getContentCharSet(final HttpEntity entity) throws ParseException {
        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }
        String charset = null;
        if (entity.getContentType() != null) {
            HeaderElement values[] = entity.getContentType().getElements();
            if (values.length > 0) {
                NameValuePair param = values[0].getParameterByName("charset");
                if (param != null) {
                    charset = param.getValue();
                }
            }
        }
        if (StringUtils.isEmpty(charset)) {
            charset = "UTF-8";
        }
        return charset;
    }

    /**
     * Get请求
     * @param uri 请求的URI
     * @param params URL格式如下:http://xxx?a={a}&b={b}
     * @return 远程服务器相应,如果状态不是200,则返回null
     */
    public static String doGet(String uri, Map<String, String> params) throws Exception {
        HttpGet httpGet = null;
        CloseableHttpResponse response = null;
        try {
            if (params != null) {
                uri = new UriTemplate(uri).expand(params).toString();
            }
            httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            System.out.println(response);
            if (response == null || response.getStatusLine().getStatusCode() != 200) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            //使用EntityUtils的toString方法,传递编码,默认编码是ISO-8859-1
            return EntityUtils.toString(entity, getContentCharSet(entity));
        } catch (Exception e) {
            throw e;
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
    }

}