HttpClient3实现HTTPS不校验证书

本文介绍了一种无需将证书导入JDK即可访问HTTPS请求的方法。通过创建一个信任任何证书的类,实现了对HTTPS请求的正常访问,避免了SSL错误。文中详细展示了如何自定义SSL上下文和信任管理器,并提供了具体的代码示例。

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

 正常情况访问https请求是自身是需要校验证书否则报SSL错误,实现不许导入证书到JDK即可正常访问https

 1、实现信任任何证书的类

package com.trunkbow.comm.serviceTest;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

public class MySSLProtocolSocketFactory implements ProtocolSocketFactory {

    private SSLContext sslcontext = null;

    private SSLContext createSSLContext() {
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null,
                    new TrustManager[] { new TrustAnyTrustManager() },
                    new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return sslcontext;
    }

    private SSLContext getSSLContext() {
        if (this.sslcontext == null) {
            this.sslcontext = createSSLContext();
        }
        return this.sslcontext;
    }

    public Socket createSocket(Socket socket, String host, int port,
            boolean autoClose) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(socket, host,
                port, autoClose);
    }

    public Socket createSocket(String host, int port) throws IOException,
            UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port);
    }

    public Socket createSocket(String host, int port, InetAddress clientHost,
            int clientPort) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port,
                clientHost, clientPort);
    }

    public Socket createSocket(String host, int port, InetAddress localAddress,
            int localPort, HttpConnectionParams params) throws IOException,
            UnknownHostException, ConnectTimeoutException {
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }
        int timeout = params.getConnectionTimeout();
        SocketFactory socketfactory = getSSLContext().getSocketFactory();
        if (timeout == 0) {
            return socketfactory.createSocket(host, port, localAddress,
                    localPort);
        } else {
            Socket socket = socketfactory.createSocket();
            SocketAddress localaddr = new InetSocketAddress(localAddress,
                    localPort);
            SocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
            return socket;
        }
    }

    // 自定义私有类
    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }

}

 

 2、使用(不需要把证书导入到JDK)

public static String send(String reqXml, String postUrl) {
    
        
        HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = new HttpConnectionManagerParams();

        params.setConnectionTimeout(10000);

        params.setSoTimeout(60000);

        params.setDefaultMaxConnectionsPerHost(10);

        params.setMaxTotalConnections(200);
        connectionManager.setParams(params);

        HttpClient httpClient = new HttpClient();  
        Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);   
        Protocol.registerProtocol("https", myhttps);   
        PostMethod method = new PostMethod(postUrl);
      //常规的
    /*
    HttpClient httpClient = new HttpClient(connectionManager);
    PostMethod method = new PostMethod(postUrl);
    */ method.addRequestHeader(
"Content-Type", "application/xml;charset=UTF-8"); try { method.setRequestEntity(new StringRequestEntity(reqXml, null, "utf-8")); httpClient.executeMethod(method); byte[] abyte0 = null; abyte0 = method.getResponseBody(); String res1 = EncodingUtil.getString(abyte0, method.getResponseCharSet()); String res = method.getResponseBodyAsString(); Header locationHeader = method.getResponseHeader("Content-Type"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); // this.log.debug("The page was redirected to:" + location); } else { // this.log.debug("Location field value is null."); } // this.log.debug("返回报文http头中的编码信息 :" + method.getResponseCharSet()); // this.log.debug("返回报文 :\n" + res); return res; } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } return null; }

 

转载于:https://www.cnblogs.com/atwanli/articles/4918131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值