https,httpClient 绕过证书验证的两种写法「建议收藏」

https,httpClient 绕过证书验证的两种写法「建议收藏」https,httpClient 绕过证书验证的两种写法

大家好,又见面了,我是你们的朋友全栈君。

1,转自:https://blog.csdn.net/zi413293813/article/details/43795953

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.util.Log;

/**
 * 工具类:创建一个忽略用户证书验证的httpClient实例
 * @date 2015-02-13
 * @author Barry
 */
public class CertificateValidationIgnored {
	
	public static HttpClient getNoCertificateHttpClient(String url){
		return getCertificateValidationIgnoredHttpClient();
	}
	
	private static HttpClient getCertificateValidationIgnoredHttpClient() {  
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore  
                    .getDefaultType());  
            trustStore.load(null, null);  
            //核心代码,创建一个UnVerifySocketFactory对象,验证证书时总是返回true
            SSLSocketFactory sf = new UnVerifySocketFactory(trustStore);
            
            HttpParams params = new BasicHttpParams();  
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
            SchemeRegistry registry = new SchemeRegistry();  
            registry.register(new Scheme("http", PlainSocketFactory  
                    .getSocketFactory(), 80));  
            registry.register(new Scheme("https", sf, 443));  
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(  
                    params, registry);  
            return new DefaultHttpClient(ccm, params);  
        } catch (Exception e) {  
        	Log.d("CertificateValidationIgnored", "创建忽略用户证书的HttpClient对象失败,尝试创建普通HttpClient对象");
        	e.printStackTrace();
            return new DefaultHttpClient();  
        }  
    }  
	
	/**
	 * 核心类
	 * UnVerifySocketFactory:一个验证证书时总是返回true的SSLSocketFactory的子类
	 */
	private static X509HostnameVerifier ignoreVerifier;
	private static class UnVerifySocketFactory extends SSLSocketFactory {
		SSLContext sslContext = SSLContext.getInstance("TLS");

		public UnVerifySocketFactory(KeyStore truststore)
				throws NoSuchAlgorithmException, KeyManagementException,
				KeyStoreException, UnrecoverableKeyException {
			super(truststore);

			TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

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

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

			sslContext.init(null, new TrustManager[] { tm }, null);
		}

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

		//核心代码
		@Override
		public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) {
			// TODO Auto-generated method stub
			ignoreVerifier = new X509HostnameVerifier() {
				@Override
				public void verify(String arg0, String[] arg1, String[] arg2)
						throws SSLException {
				}
				@Override
				public void verify(String arg0, X509Certificate arg1)
						throws SSLException {
				}
				@Override
				public void verify(String arg0, SSLSocket arg1)
						throws IOException {
				}
				
				//最最核心代码
				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			};
			super.setHostnameVerifier(ignoreVerifier);
		}

		@Override
		public X509HostnameVerifier getHostnameVerifier() {
			return ignoreVerifier;
		}

		@Override
		public Socket createSocket() throws IOException {
			return sslContext.getSocketFactory().createSocket();
		}
	}
		
}

2,https,json参数,绕过证书验证:

	public String sendHttpsPostjson(String url,String json, String charSet) throws Exception{  
       	logger.debug("请求地址:{}", url);
           HttpClient httpClient = null;  
           HttpPost httpPost = null;  
           String result = null;  
           	httpClient = new SSLClient();  
               httpPost = new HttpPost(url);  
               JSONObject map = JSON.parseObject(json);
               StringEntity entity = new StringEntity(map.toString(), charSet);
   			   entity.setContentEncoding(charSet);
   			   entity.setContentType("application/json");
               httpPost.setEntity(entity);
               HttpResponse response = httpClient.execute(httpPost);  
               if(response != null){
                   HttpEntity resEntity = response.getEntity();  
                   if(resEntity != null){  
                       result = EntityUtils.toString(resEntity,charSet);
                   }  
               } 
               
           return result;  
       }  
package com.http.socket;


import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * 绕过https证书认证的方法
 *
 */
public class SSLClient extends DefaultHttpClient{  
	public SSLClient() throws Exception{  
        super();  
        SSLContext ctx = SSLContext.getInstance("TLS");  
        X509TrustManager tm = new X509TrustManager() {  
                @Override  
                public void checkClientTrusted(X509Certificate[] chain,  
                        String authType) throws CertificateException {  
                }  
                @Override  
                public void checkServerTrusted(X509Certificate[] chain,  
                        String authType) throws CertificateException {  
                }  
                @Override  
                public X509Certificate[] getAcceptedIssuers() {  
                    return null;  
                }  
        };  
        ctx.init(null, new TrustManager[]{tm}, null);  
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
        ClientConnectionManager ccm = this.getConnectionManager();  
        SchemeRegistry sr = ccm.getSchemeRegistry();  
        sr.register(new Scheme("https", 443, ssf));  
    }  
}  

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/106089.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(1)


相关推荐

  • python和java和c语言的区别-python c 和java的区别有哪些「建议收藏」

    python和java和c语言的区别-python c 和java的区别有哪些「建议收藏」一、pythonpython比较容易学习,语法很简单,融入了很多现代编程语言的特性。python的库非常丰富,可以迅速地开发程序,无论是网站还是小游戏都非常方便。不过,python的脚本的运行效率较低,不适合对运行效率要求较高的程序。Python是一种脚本语言。它更适合用来做算法。Python简单易学,对于新手来讲是编程入门的好选择。Python其实也是基于C++创造的,它们的区别主要体现在,C+…

  • CAP理论中, P(partition tolerance, 分区容错性)的合理解释

    CAP理论中, P(partition tolerance, 分区容错性)的合理解释在CAP理论中,对partitiontolerance分区容错性的解释一般指的是分布式网络中部分网络不可用时,系统依然正常对外提供服务,而传统的系统设计中往往将这个放在最后一位.这篇文章对这个此进行了分析和重新定义,并说明了在不同规模分布式系统中的重要性.The‘CAP’theoremisahottopicinthedesignofdistributeddat…

  • int型转换为long型遇到的一个小问题

    int型转换为long型遇到的一个小问题LeetCode上有一道题:给出一个数n,求(0,n)之间素数的个数。然后我采用埃拉托斯特尼筛法在每次找到一个素数时,将能被素数整除的数排除掉。但是,在进行int类型转换的时候会报:java.lang.ArrayIndexOutOfBoundsException代码如下:publicintcountPrimes(intn){boolea…

  • 与运算或运算非运算异或运算是什么_俄称击退乌军进攻

    与运算或运算非运算异或运算是什么_俄称击退乌军进攻按位与运算符(&)参加运算的两个数据,按二进制位进行“与”运算。运算规则:0&0=0;  0&1=0;   1&0=0;    1&1=1;      即:两位同时为“1”,结果才为“1”,否则为0例如:3&5 即00000011&00000101=00000001  因此,3&5的值得1。 另,负数按补码形式参加按位与运算。“与运算”的特殊用途:(1

  • 列式数据库_开源列式数据库

    列式数据库_开源列式数据库列式数据库是相对于行式存储的数据库,Oracle、MySQL、SQLServer等数据库都是采用的行式存储(Row-based),而列式数据库是将数据按照列存储到数据库中,这样做的好处是可以大量降低系统的I/O,适合于分布式文件系统,不足在于功能相对有限。典型产品:HBase等。…

    2022年10月22日
  • linux安装redis_redis安装配置

    linux安装redis_redis安装配置1、在Linux下安装Redis服务。2、Redis安装部署。3、Redis制作开机自启动服务。

发表回复

您的电子邮箱地址不会被公开。

评论列表(2条)

  • 匿名
    匿名 2022年5月11日 下午10:12

    最后一个方法的类过期了有没有其他方案呢

  • 全栈程序员栈长
    全栈程序员-用户IM 2022年5月23日 上午10:05

    @匿名网站查一查.

关注全栈程序员社区公众号