httpclient-ssl+https校验+springboot ssl

来源:互联网 发布:2015年汽车产销量数据 编辑:程序博客网 时间:2024/06/07 17:43

HttpClientUtil

/** * HTTPClient工具类 */public class HttpClientUtil {    private static final String EMPTY_STR = "";    private static final String UTF_8 = "UTF-8";    private static final int MAX_TIMEOUT = 100000;    private static PoolingHttpClientConnectionManager cm;    private static RequestConfig requestConfig;    private static Logger logger = Logger.getLogger(HttpClientUtil.class);    private static CloseableHttpClient httpClient;    private static final String keyStorePath = "d:/keystore/xxx.keystore";    private static final String keyStorePwd = "xxxx";    public static void main(String[] args) {        httpGetRequest("https://www.baidu.com");    }    private static CloseableHttpClient getHttpClient() {        try {            KeyStore trustStore = null;//            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());//            FileInputStream inputStream = new FileInputStream(new File(keyStorePath));//            trustStore.load(inputStream, keyStorePwd.toCharArray());            // 相信自己的CA和所有自签名的证书            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);            // 设置协议http和https对应的处理socket链接工厂的对象            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()                    .register("http", PlainConnectionSocketFactory.INSTANCE)                    .register("https", sslConnectionSocketFactory)                    .build();            initHttpClientConnectionManager(socketFactoryRegistry);            return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();        } catch (KeyStoreException e) {            e.printStackTrace();        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (KeyManagementException e) {            e.printStackTrace();        }        return null;    }    private static void initHttpClientConnectionManager(Registry<ConnectionSocketFactory> registry) {        if (cm == null) {            cm = new PoolingHttpClientConnectionManager(registry);            cm.setMaxTotal(50);// 整个连接池最大连接数            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2            RequestConfig.Builder configBuilder = RequestConfig.custom();            // 设置连接超时            configBuilder.setConnectTimeout(MAX_TIMEOUT);            // 设置读取超时            configBuilder.setSocketTimeout(MAX_TIMEOUT);            // 设置从连接池获取连接实例的超时            configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);            // 在提交请求之前 测试连接是否可用            configBuilder.setStaleConnectionCheckEnabled(true);            requestConfig = configBuilder.build();        }    }    /**     * @param url     * @return     */    public static String httpGetRequest(String url) {        HttpGet httpGet = new HttpGet(url);        if (StringUtils.isNotBlank(url)) {            return getResult(httpGet);        }        return null;    }    public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {        URIBuilder ub = new URIBuilder();        ub.setPath(url);        List<NameValuePair> pairs = covertParams2NVPS(params);        ub.setParameters(pairs);        HttpGet httpGet = new HttpGet(ub.build());        return getResult(httpGet);    }    public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)            throws URISyntaxException {        URIBuilder ub = new URIBuilder();        ub.setPath(url);        List<NameValuePair> pairs = covertParams2NVPS(params);        ub.setParameters(pairs);        HttpGet httpGet = new HttpGet(ub.build());        for (Map.Entry<String, Object> param : headers.entrySet()) {            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));        }        return getResult(httpGet);    }    public static String httpPostRequest(String url) {        HttpPost httpPost = new HttpPost(url);        return getResult(httpPost);    }    public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {        HttpPost httpPost = new HttpPost(url);        List<NameValuePair> pairs = covertParams2NVPS(params);        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));        return getResult(httpPost);    }    public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)            throws UnsupportedEncodingException {        HttpPost httpPost = new HttpPost(url);        for (Map.Entry<String, Object> param : headers.entrySet()) {            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));        }        List<NameValuePair> pairs = covertParams2NVPS(params);        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));        return getResult(httpPost);    }    private static List<NameValuePair> covertParams2NVPS(Map<String, Object> params) {        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();        for (Map.Entry<String, Object> param : params.entrySet()) {            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));        }        return pairs;    }    private static String getResult(HttpRequestBase request) {        if (httpClient == null) {            httpClient = getHttpClient();        }        try {            CloseableHttpResponse response = httpClient.execute(request);            HttpEntity entity = response.getEntity();            if (entity != null) {                // long len = entity.getContentLength();// -1 表示长度未知                String result = EntityUtils.toString(entity);                response.close();                return result;            }        } catch (ClientProtocolException e) {            logger.error(e.getMessage(), e);        } catch (IOException e) {            logger.error(e.getMessage(), e);        }        return EMPTY_STR;    }}

https校验类

MyX509Test

import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import java.io.InputStreamReader;import java.net.URL;public class MyX509Test {    public static void main(String[] args) {        try {            httpGetRequest("https://localhost:8443/user/1");        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    public static void httpGetRequest(String url) throws Exception {        // 创建SSLContext对象,并使用我们指定的信任管理器初始化        TrustManager[] tm = {new MyX509TrustManager()};        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");        sslContext.init(null, tm, new java.security.SecureRandom());        // 从上述SSLContext对象中得到SSLSocketFactory对象        SSLSocketFactory ssf = sslContext.getSocketFactory();        // 创建URL对象        URL myURL = new URL(url);        // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象        HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();        httpsConn.setSSLSocketFactory(ssf);        // 取得该连接的输入流,以读取响应内容        InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");        // 读取服务器的响应内容并显示        int respInt = insr.read();        while (respInt != -1) {            System.out.print((char) respInt);            respInt = insr.read();        }    }}

MyX509TrustManager

/** * 自定义信任管理器 * <p> * https加密 */public class MyX509TrustManager implements X509TrustManager {    X509TrustManager sunJSSEX509TrustManager;    private static final String TRUST_MANAGER_ALGORITHM = "SunX509";    private static final String TRUEST_PROVIDER = "SunJSSE";    private static final String CERTS_PWD = "123123";    private static final String FILE_PATH = "D:\\keystore/kyo.keystore";    // 构造方法初始化证书信息    public MyX509TrustManager() throws Exception {        // 获得keystore实例        KeyStore ks = KeyStore.getInstance("jks");        // keystore文件流、密码        ks.load(new FileInputStream(FILE_PATH), CERTS_PWD.toCharArray());        // algorithm:加密方式        // provider:提供者        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TRUST_MANAGER_ALGORITHM, TRUEST_PROVIDER);        // 信任管理器初始化证书        tmf.init(ks);        TrustManager[] tms = tmf.getTrustManagers();        for (TrustManager tm : tms) {            if (tm instanceof X509TrustManager) {                sunJSSEX509TrustManager = (X509TrustManager) tm;                return;            }        }        // 如果都没有发现,抛出异常        throw new Exception("Couldn'tinitialize!");    }    // 检测客户端是否信任程序    public void checkClientTrusted(X509Certificate[] chain, String authType) {        try {            sunJSSEX509TrustManager.checkClientTrusted(chain, authType);        } catch (CertificateException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    // 检测服务器端是否信任程序    public void checkServerTrusted(X509Certificate[] chain, String authType) {        try {            sunJSSEX509TrustManager.checkServerTrusted(chain, authType);        } catch (CertificateException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    // 获得信任的发型证书    public X509Certificate[] getAcceptedIssuers() {        return sunJSSEX509TrustManager.getAcceptedIssuers();    }}

spring boot SSL

application.yml

server:  port: 8443  tomcat:    max-connections: 2000    max-threads: 200    uri-encoding: UTF-8#  ssl:#    key-alias: tomcat#    key-password: tomcat#    enabled: true#    key-store: d:\tomcat.keystore  ssl:    key-alias: zlf    key-password: 111111    enabled: true    key-store: classpath:zlf.keystore

Application

@SpringBootApplicationpublic class Application {    @Bean    public EmbeddedServletContainerFactory servletContainer() {        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {            @Override            protected void postProcessContext(Context context) {                SecurityConstraint securityConstraint = new SecurityConstraint();                securityConstraint.setUserConstraint("CONFIDENTIAL");                SecurityCollection collection = new SecurityCollection();                collection.addPattern("/*");                securityConstraint.addCollection(collection);                context.addConstraint(securityConstraint);            }        };        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());        return tomcat;    }    private Connector initiateHttpConnector() {        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");        connector.setScheme("http");        connector.setPort(8000);        connector.setSecure(false);        connector.setRedirectPort(8443);        return connector;    }    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

keytool命令

//生成keystorekeytool -genkeypair -alias "zlf" -keyalg "RSA" -keystore "zlf.keystore"  keytool -genkeypair -alias "kyo" -keyalg "RSA" -keystore "kyo.keystore"  //查看keystorekeytool -list -keystore test.keystore  //详细keytool -list -keystore test.keystore -v//导出证书keytool -export -alias zlf -keystore zlf.keystore -storepass 111111 -rfc -file zlf.cer//导入证书keytool -import -keystore d:/keystore/kyo.keystore -file d:/keystore/zlf.cer
原创粉丝点击