httpclient 4 忽略ssl证书

本文详细介绍了一种在Java中实现HTTPS请求时绕过证书验证的方法,通过自定义SSLContext和TrustStrategy,允许应用程序信任所有服务器证书,解决因证书问题导致的连接失败。此策略适用于开发测试环境,但在生产环境中应谨慎使用。
摘要由CSDN通过智能技术生成
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by chenganshi on 16/9/17.
 */
public class Test2 {

    public static void main(String[] args) throws Exception {
        /*CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
        httpClient.execute(new HttpGet("https://kyfw.12306.cn/otn/regist/init"));*/
        main2();
    }

    public static void main2() throws Exception {
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                })
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                NoopHostnameVerifier.INSTANCE);
        /*SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                new DefaultHostnameVerifier());*/
        /*SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext);*/
        PlainConnectionSocketFactory plainConnectionSocketFactory = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslsf)
                .register("http", plainConnectionSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();
        ResponseHandler<String> handler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        };
        String baidu = httpClient.execute(new HttpGet("http://www.baidu.com"), handler);
        System.out.println("baidu[" + baidu + "]");
        String ticket = httpClient.execute(new HttpGet("https://kyfw.12306.cn/otn/regist/init"), handler);
        //报错,证书和域名不匹配!Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: Host name '211.162.177.45' does not match the certificate subject provided by the peer (CN=kyfw.12306.cn, OU=铁路客户服务中心, O=Sinorail Certification Authority, C=CN)
        //String ticket = httpClient.execute(new HttpGet("https://211.162.177.45/otn/regist/init"), handler);
        System.out.println("ticket[" + ticket + "]");

        String gitosc = httpClient.execute(new HttpGet("https://git.oschina.net/"), handler);
        System.out.println("--------");
        System.out.println(gitosc);
    }

}

转载于:https://my.oschina.net/cashi/blog/747764

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值