httpclient 4.5.2 https协议时忽略服务器证书

1maven dependence
dependency>
    groupId>org.apache.httpcomponentsgroupId>
    artifactId>httpclientartifactId>
    version>4.5.2version>
dependency>
2. 测试类
package com.iraid.test;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
 
import javax.net.ssl.SSLContext;
 
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
 
/**
 * 使用 httpclient4.5 进行 https 通讯,
 * 采用双向认证, 连接池管理connection
 * 
 * @author wangfeihu
 *
 */
public class HttpClientforSSL {
 
    public static HttpClientConnectionManager CONNECTION_MANAGER = null;
 
    /**
     * 初始化 connection manager.
     * @param keyStoreFile
     * @param keyStorePass
     * @param trustStoreFile
     * @param trustStorePass
     * @throws Exception
     */
    public void init(String keyStoreFile, String keyStorePass,
            String trustStoreFile, String trustStorePass) throws Exception {
        System.out.println("init conection pool...");
 
        InputStream ksis = new FileInputStream(new File(keyStoreFile));// 私钥证书
        InputStream tsis = new FileInputStream(new File(trustStoreFile));// 信任证书库
 
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(ksis, keyStorePass.toCharArray());
 
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsis, trustStorePass.toCharArray());
 
        SSLContext sslContext = SSLContexts.custom()
                .loadKeyMaterial(ks, keyStorePass.toCharArray())
                // 如果有 服务器证书
                .loadTrustMaterial(ts, new TrustSelfSignedStrategy())
                // 如果没有服务器证书,可以采用自定义 信任机制
                // .loadTrustMaterial(null, new TrustStrategy() {
                //
                // // 信任所有
                // public boolean isTrusted(X509Certificate[] arg0,
                // String arg1) throws CertificateException {
                // return true;
                // }
                //
                // })
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 
        Registry registry = RegistryBuilder
                . create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", sslsf).build();
        ksis.close();
        tsis.close();
        CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(registry);
 
    }
 
    /**
     * do post
     * @param url
     * @param params
     * @throws Exception
     */
    public void post(String url, String params) throws Exception {
        if (CONNECTION_MANAGER == null) {
            return;
        }
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(CONNECTION_MANAGER).build();
        HttpPost httpPost = new HttpPost(url);
 
        httpPost.setEntity(new StringEntity(params,
                ContentType.APPLICATION_JSON));
 
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        System.out.println(resp.getStatusLine());
        InputStream respIs = resp.getEntity().getContent();
        String content = convertStreamToString(respIs);
        System.out.println(content);
        EntityUtils.consume(resp.getEntity());
    }
 
     
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


如果没有证书或者秘钥上面的init方法直接可以写成这样:

/**
	 * httpclient4.5.2版
	 * 忽略服务器证书,采用信任机制
	 * @return
	 */
	public static HttpClientConnectionManager init(){
		try {
			SSLContext sslContext  = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
				
				@Override
				public boolean isTrusted(X509Certificate[] arg0, String arg1)
						throws CertificateException {
					// TODO Auto-generated method stub
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, new String[] { "TLSv1" }, null,
	                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Registry registry = RegistryBuilder
	                . create()
	                .register("http", PlainConnectionSocketFactory.INSTANCE)
	                .register("https", sslsf).build();
	        return new PoolingHttpClientConnectionManager(registry);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
在main方法中调用getConn方法
public static void main(String[] args) {
		
		HttpClientConnectionManager clientConnectionManager = init();
		if(clientConnectionManager != null){
			CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(clientConnectionManager).build();
			String url = "http://admod-analyse.com:8080";
			getConn(httpClient, url);
		}
	}



原文地址:http://www.68iis.com/server/Linuxserver/4181_2.html

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值