httpclient3.1跳过ssl验证

原来的老项目调用一个Http的服务,最近http的服务调整成了https,因此需要调整一下,网上大部分都是4.5以上版本,3.1版本处理方法比较少,因此记录一下

一、实现两个类

1.MyX509TrustManager

复制代码
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
 
public class MyX509TrustManager implements X509TrustManager {
    /* (non-Javadoc)
    * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String)
    */
    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
 
    }
    /* (non-Javadoc)
     * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String)
     */
    public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
 
    }
    /* (non-Javadoc)
     * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
     */
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

2.MySecureProtocolSocketFactory

项目使用的jdk版本是1.8,jdk版本默认协议需要指定一下,因此SSLContext context = SSLContext.getInstance("TLSv1.2");

复制代码
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
 
public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {
 
    //添加一个属性,主要目的获取ssl跳过验证
    private SSLContext sslContext = null;
    /**
     * Constructor for MySecureProtocolSocketFactory.
     */
    public MySecureProtocolSocketFactory() {
    }
    /**
     * 创建一个获取SSLContext的方法,导入MyX509TrustManager进行初始化
     * @return
     */
    private static SSLContext createEasySSLContext() {
        try {
            SSLContext context = SSLContext.getInstance("TLSv1.2");
            context.init(null, new TrustManager[] { new MyX509TrustManager() },
                    null);
            return context;
        } catch (Exception e) {
            throw new HttpClientError(e.toString());
        }
    }
 
    /**
     * 判断获取SSLContext
     * @return
     */
    private SSLContext getSSLContext() {
        if (this.sslContext == null) {
            this.sslContext = createEasySSLContext();
        }
        return this.sslContext;
    }
    //后面的方法基本上带入相关参数
    /*
     * (non-Javadoc)
     *
     * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,
     *      int, java.net.InetAddress, int)
     */
    public Socket createSocket(String host, int port, InetAddress clientHost,int clientPort) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port,clientHost, clientPort);
    }
 
    /*
     * (non-Javadoc)
     *
     * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,
     *      int, java.net.InetAddress, int,
     *      org.apache.commons.httpclient.params.HttpConnectionParams)
     */
    public Socket createSocket(final String host, final int port,final InetAddress localAddress, final int localPort,
                               final HttpConnectionParams params) throws IOException,UnknownHostException, ConnectTimeoutException {
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }
        int timeout = params.getConnectionTimeout();
        if (timeout == 0) {
            return createSocket(host, port, localAddress, localPort);
        } else {
            return ControllerThreadSocketFactory.createSocket(this, host, port,localAddress, localPort, timeout);
        }
    }
 
    /*
     * (non-Javadoc)
     *
     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
     */
    public Socket createSocket(String host, int port) throws IOException,UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port);
    }
 
    /*
     * (non-Javadoc)
     *
     * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
     */
    public Socket createSocket(Socket socket, String host, int port,boolean autoClose) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(socket, host,port, autoClose);
    }
}

最后声明MySecureProtocolSocketFactory加入Protocol就可以了。

复制代码
        //声明
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        //加入相关的https请求方式
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        //发送请求
        org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
        GetMethod httpget = new GetMethod(url);
        System.out.println("======https的服务地址url:" + url);
        try {
            httpclient.executeMethod(httpget);
            return httpget.getResponseBodyAsString();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        } finally {
            httpget.releaseConnection();
        }

实现完后自信满满重新打包更新上正式环境,结果报错了。。。

java 复制代码
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates do not conform to algorithm constraints


	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)


	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)


	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)


	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)


	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)


	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)


	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)


	at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)


	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)


	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)

百度一下这个问题,证书不符合算法约束,基本都是修改配置文件$JAVA_HOME/jre/lib/security/java.security,但是项目是docker部署的,jdk用的是docker里面的,外面服务器里的jdk版本都是11,那每次更新服务都得手动改配置也太麻烦了吧。。。

===================================================================

后面找到一篇文章,修改前面的实现类,把自己实现的类改写成继承新的抽象类:X509ExtendedTrustManager即可,代码如下:

java 复制代码
//public class MyX509TrustManager implements X509TrustManager {
public class MyX509TrustManager extends X509ExtendedTrustManager {
//实现方法,所有方法都是空方法
}

再次更新代码,问题解决!

参考:httpclient 3.1跳过https请求SSL的验证_鼓逗猫柠的博客-CSDN博客
https://www.cnblogs.com/flyingeagle/articles/7508207.html

相关推荐
1560820721912 分钟前
基于7VX690T FPGA实现万兆TCP/IP资源和性能测试
网络协议·tcp/ip·fpga开发
踏浪无痕3 小时前
线上偶发 502 排查:用 Netty 成功复现 KeepAlive 时间窗口案例实战(附完整源码)
运维·网络协议
北京耐用通信3 小时前
告别“牵一发而动全身”:耐达讯自动化Profibus PA分线器为石化流量计网络构筑安全屏障
人工智能·网络协议·安全·自动化·信息与通信
Sinowintop3 小时前
易连EDI-EasyLink无缝集成之消息队列Kafka
分布式·网络协议·kafka·集成·国产化·as2·国产edi
阿巴~阿巴~11 小时前
自定义协议设计与实践:从协议必要性到JSON流式处理
服务器·网络·网络协议·json·操作系统·自定义协议
jinxinyuuuus17 小时前
GTA 风格 AI 生成器:跨IP融合中的“视觉语义冲突”与风格适配损失
人工智能·网络协议
嵌入式-小王19 小时前
每天掌握一个网络协议----ICMP
网络·网络协议·ping
Awkwardx19 小时前
Linux网络编程—应用层协议HTTP
网络·网络协议·http
Running_slave20 小时前
你应该了解的TCP滑窗
前端·网络协议·tcp/ip
无证驾驶梁嗖嗖1 天前
无需公网 IP,MongoDB 也能跨环境访问?试试这个实用方案
网络协议·tcp/ip·mongodb