关闭

绕过证书校验https协议URL

506人阅读 评论(0) 收藏 举报
分类:
校验Http协议URL 并获取内容:   HttpClient 测试url连通 取得content  

在项目中遇到需要校验https协议的url报出SSL异常问题。先前写过一片校验http协议的文章不适合校验非信任域证书的https的URL,会报SSL异常,原因是程序里加载远程应用的证书。其实我们可以绕过证书只校验URL。

根据别人的代码做了一下修改,代码如下:


package com.williamwu.service;

import java.net.SocketTimeoutException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

@SuppressWarnings("deprecation")
public class ConnectUtils {
	/**
	 * 自定义私有类:绕开HTTPS证书校验
	 */
	private static class EasyTrustManager implements X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}                                                                                                                                                                                                                                                                                   

		public void checkClientTrusted(X509Certificate[] certs, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] certs, String authType) {
		}
	}
	
	public static int isSSLConnected(String httpUrl) throws SocketTimeoutException, Exception {
		int statusCode = 0;
		
		HttpClient hc = new DefaultHttpClient();
		// 连接超时设为6秒
		hc.getParams().setIntParameter("http.connection.timeout", 6000);
		// 连接成功后等待返回的超时设为8秒
		hc.getParams().setIntParameter("http.socket.timeout", 8000);		
		
		HttpGet httpGet = new HttpGet(httpUrl);
		
		try 
		{
			// HTTPS应绕开证书验证
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new TrustManager[] { new EasyTrustManager() },
					null);
			SSLSocketFactory factory = new SSLSocketFactory(context,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", 443, factory);
			hc.getConnectionManager().getSchemeRegistry().register(https);

			HttpResponse response = hc.execute(httpGet);
			statusCode = response.getStatusLine().getStatusCode();
		} catch (Exception e) {
			httpGet.abort();
			throw e;
		} finally {
			hc.getConnectionManager().shutdown();
		}
		return statusCode;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1597次
    • 积分:44
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档