发送https请求时绕过证书验证

本文介绍了一种在Java中创建HTTPS客户端的方法,该客户端绕过了通常的证书验证过程,适用于测试环境或特殊情况下的需求。文章详细展示了如何配置Apache HttpClient以信任所有SSL证书,并提供了连接池管理及超时策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.demo.http;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;

/**
 * 获取https访问权限
 *
 * @author LVXY 2016年11月18日 上午11:51:15
 * @version V2.0
 *
 */
public abstract class SSLUtils {
    private static final int MAXTOTAL = 500;//默认最大连接数
    private static final int DEFAULTMAXPERROUTE = 500;//默认每个主机的最大链接数
    private static HttpRequestRetryHandler httpRequestRetryHandler = new DefaultHttpRequestRetryHandler();//默认不进行重试处理
    private static CloseableHttpClient httpClient;
    
    static {
        //采用绕过验证的方式处理https请求
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        };
        SSLContext sslContext = createIgnoreVerifySSL();
        
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
        
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();
        
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(MAXTOTAL);// 设置最大连接数
        cm.setDefaultMaxPerRoute(DEFAULTMAXPERROUTE);// 设置每个路由的默认连接数

        //连接保持时间
        ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (NumberFormatException ignore) {
                        }
                    }
                }
                return 30 * 1000;
            }
        };

        httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setRetryHandler(httpRequestRetryHandler)
                .setKeepAliveStrategy(myStrategy)
                .build();
    }
    
    
    public static CloseableHttpClient createSSLInsecureClient() {
        try {
            return httpClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  HttpClients.createDefault();
    }
    
    
    /**
     * 请求重试处理 
     * 默认不进行任何重试
     */
    private static class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    }

    
    public static class IdleConnectionMonitorThread extends Thread {
        private final PoolingHttpClientConnectionManager connMgr;

        public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
            super();
            this.connMgr = connMgr;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    sleep(30000);
                    connMgr.closeExpiredConnections(); // 关闭过期的连接
                    connMgr.closeIdleConnections(30, TimeUnit.SECONDS); // 关闭空闲时间超过30秒的连接
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    
    /**
     * 绕过验证
     *  
     * @return
     * @throws NoSuchAlgorithmException 
     * @throws KeyManagementException 
     */
    public static SSLContext createIgnoreVerifySSL() {
        SSLContext sslContext = null;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {//信任所有
                    return true;
                }
            }).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }

        return sslContext;
    }

    
    
    
    //代码备份
/*    public static CloseableHttpClient createSSLInsecureClientBak() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {//信任所有
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return  HttpClients.createDefault();
    }*/
}

转载于:https://my.oschina.net/haokevin/blog/1841007

HTTPS是一种安全的HTTP协议,它通过SSL/TLS加密来保护数据传输,确保了通信过程的安全性和隐私性。默认情况下,浏览器或HTTP客户端在发送HTTPS请求验证服务器的SSL证书,包括证书的有效期、发行者以及证书链的完整性,以防止中间人攻击。 如果你想强制HTTPS请求绕过SSL验证,通常是在一些特定场景下,比如测试环境需要模拟生产环境,或者为了某种原因(如性能测试)暂禁用严格的SSL检查。这,可以采取以下几种方法: 1. **Python** (requests库):使用`verify=False`或提供自签名证书路径,如`verify=False`或`cert=('/path/to/cert.pem', '/path/to/key.pem')`。 ```python import requests response = requests.get('https://example.com', verify=False) ``` 2. **JavaScript** (fetch API): 设置`credentials: 'include'` 和 `rejectUnauthorized: false` 可能会导致警告,因为这会让敏感信息暴露在未授权的环境中。 ```javascript fetch('https://example.com', { mode: 'no-cors', credentials: 'include', rejectUnauthorized: false }) ``` 3. **浏览器控制台**: 短期内,可以在开发者工具网络面板中勾选“忽略SSL证书错误”进行调试,但这仅适用于当前会话,并不推荐用于生产环境。 然而,不验证SSL是出于安全考虑的一个明确妥协,所以在实际应用中应谨慎使用,并确保对后果有充分理解。除非有特殊需求,否则强烈建议始终启用严格的SSL验证,以保护用户的数据安全。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值