httpclient 3.1跳过https请求SSL的验证

一、因为在使用https发送请求的时候会涉及,验证方式。但是这种方式在使用的时候很不方便。特别是在请求外部接口的时候,所以这我写了一个跳过验证的方式。(供参考)

二、加入包,这里用的是commons-httpclient 3.1 的包。一般请求采用最新的httpclient4.5就可以了

<dependency>
  <groupId>commons-httpclient</groupId>
  <artifactId>commons-httpclient</artifactId>
  <version>3.1</version>
</dependency>

三、这里我们实现3个类

1、MyX509TrustManager(这个方法直接实现X509TrustManager,X509TrustManager在javax.net.ssl.X509TrustManager里面)

这里直接实现不用改任何东西

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(这里我们需要用到SSLContext,还需要改写一个实现SecureProtocolSocketFactory的方法)

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("SSL");
            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);
    }
}

3、然后就是httpclient了,这里实现的方式很单间了,只要声明MySecureProtocolSocketFactory加入就可以了Protocol

import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {

    public static String doGet(String url) throws Exception {
        //声明
        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("======url:" + url);
        try {
            httpclient.executeMethod(httpget);
            return httpget.getResponseBodyAsString();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        } finally {
            httpget.releaseConnection();
        }
    }

}

四、这里基本上就完成了,在会用的时候只要声明MySecureProtocolSocketFactory加入就可以了Protocol,然后就可以实现验证的跳过过了

转自:http://www.cnblogs.com/ll409546297/p/7154542.html

时间: 2024-10-31 17:42:33

httpclient 3.1跳过https请求SSL的验证的相关文章

HTTPS请求 SSL证书验证

import urllib2 url = "https://www.12306.cn/mormhweb/" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"} request = urllib2.Request(ur

httpclient跳过https请求的验证

一.因为在使用https发送请求的时候会涉及,验证方式.但是这种方式在使用的时候很不方便.特别是在请求外部接口的时候,所以这我写了一个跳过验证的方式.(供参考) 二.加入包,这里用的是commons-httpclient 3.1 的包.一般请求采用最新的httpclient4.5就可以了 <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</

python2/3 https忽略ssl证书验证

import ssl ssl._create_default_https_context = ssl._create_unverified_context InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised

使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL

这里使用的是HttpComponents-Client-4.1.2 1 package com.jadyer.util; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.IOException; 7 import java.security.KeyManagementException; 8 import java

HTTPClient 发送HTTPS请求

HTTPClient 发送HTTP请求就不多说了, 现在给出发送HTTPS请求, 主要思路是忽略证书验证. /** * * @param url * @param contextType "image/jpeg","application/Json" * @return */ public static byte[] sendHttpsGetUrl(HttpClient httpClient1 ,String url,String contextType) { //

接口测试——HttpClient工具的https请求、代理设置、请求头设置、获取状态码和响应头

转自:https://www.cnblogs.com/hong-fithing/p/7617855.html https请求 https协议(Secure Hypertext Transfer Protocol) : 安全超文本传输协议, HTTPS以保密为目标研发, 简单讲HTTPS协议是由SSL+HTTP协议构建的可进行加密传输. 身份认证的网络协议, 其安全基础是SSL协议, 因此加密的详细内容请看SSL. 全称Hypertext Transfer Protocol overSecure

httpclient绕过证书验证进行HTTPS请求

http请求是我们常用的一种web应用的应用层协议,但是由于它的不安全性,现在正在逐渐向https协议过渡.https协议是在http的基础上进行了隧道加密,加密方式有SSL和TLS两种.当server用https协议进行数据交换后,client请求server时会对server的证书进行校验,如果server端证书为四大证书机构颁发的证书或者其授权机构颁发的证书,则允许进一步请求,否则会警告证书不受信任.更多信息可参考https://www.cnblogs.com/handsomeBoys/p

通过 Apache Commons HttpClient 发送 HTTPS 请求

1.通过 HTTPS 发送 POST 请求: 2.HTTPS 安全协议采用 TLSv1.2: 3. 使用代理(Proxy)进行 HTTPS 访问: 4.指定 Content-Type 为:application/x-www-form-urlencoded: 5.HTTPS  请求时加载客户端证书(Client Certificate): 6.忽略服务器端证书链(Server Certificate Chain)的校验(Validate). public static void main(Stri

封装HttpClient进行http请求与https请求

一.https忽略证书 /** * 用于进行Https请求的HttpClient * * @author joey * */ public class SSLClient { public static CloseableHttpClient createSSLClientDefault(){ try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { //