惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
博客园 - Franky
GbyAI
GbyAI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
aimingoo的专栏
aimingoo的专栏
博客园_首页
MongoDB | Blog
MongoDB | Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recent Announcements
Recent Announcements
Scott Helme
Scott Helme
有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
C
CERT Recently Published Vulnerability Notes
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Jina AI
Jina AI
F
Fortinet All Blogs
N
Netflix TechBlog - Medium
L
LangChain Blog
L
LINUX DO - 最新话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Hacker News: Front Page
MyScale Blog
MyScale Blog
P
Palo Alto Networks Blog
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
AI
AI
T
Troy Hunt's Blog
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
S
Secure Thoughts
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
人人都是产品经理
人人都是产品经理
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
S
Security @ Cisco Blogs
Cloudbric
Cloudbric
E
Exploit-DB.com RSS Feed
Attack and Defense Labs
Attack and Defense Labs

博客园 - lzhou666

spring cloud开发、部署注意 使用Spring Sleuth和Zipkin跟踪微服务 多线程处理中Future的妙用 hystrix-turbine 监控的使用 spring boot/cloud 应用监控 spring boot 自动部署方案 使用spring boot和thrift、zookeeper建立微服务 计数器 使用docker发布spring cloud应用 综合使用spring cloud技术实现微服务应用 Spring cloud实现服务注册及发现 使用spring cloud实现分布式配置管理 spring cloud教程之使用spring boot创建一个应用 7天学会spring cloud教程 微服务开发的12项要素 一句话概括下spring框架及spring cloud框架主要组件 翻译-服务注册与发现 翻译-微服务API Gateway 微服务分布式事务的一些思考
HttpClient4.5 SSL访问工具类
lzhou666 · 2016-12-08 · via 博客园 - lzhou666

要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类。

/**
解决httpClient对https请求报不支持SSLv3问题.
JDK_HOME/jrebcurity/java.security 文件中注释掉:
jdk.certpath.disabledAlgorithms=MD2
jdk.tls.disabledAlgorithms=DSA(或jdk.tls.disabledAlgorithms=SSLv3)
*/
public class HttpsUtil {
	public static CloseableHttpClient createClient() throws Exception{
		TrustStrategy trustStrategy = new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] xc, String msg)
					throws CertificateException {
				return true;
			}
		};
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(trustStrategy);
		HostnameVerifier hostnameVerifierAllowAll = new HostnameVerifier() {
			@Override
			public boolean verify(String name, SSLSession session) {
				return true;
			}
		};
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				builder.build(), new String[] { "SSLv2Hello", "SSLv3", "TLSv1",
						"TLSv1.1", "TLSv1.2" }, null, hostnameVerifierAllowAll);
		
		HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
		    public boolean retryRequest(
		            IOException exception,
		            int executionCount,
		            HttpContext context) {
		    	//重试设置
		        if (executionCount >= 5) {
		            // Do not retry if over max retry count
		            return false;
		        }
		        if (exception instanceof InterruptedIOException) {
		            // Timeout
		            return false;
		        }
		        if (exception instanceof UnknownHostException) {
		            // Unknown host
		            return false;
		        }
		        if (exception instanceof ConnectTimeoutException) {
		            // Connection refused
		            return false;
		        }
		        if (exception instanceof SSLException) {
		            // SSL handshake exception
		            return false;
		        }
		        HttpClientContext clientContext = HttpClientContext.adapt(context);
		        HttpRequest request = clientContext.getRequest();
		        boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
		        if (idempotent) {
		            return true;
		        }
		        return false;
		    }
		};		
		RequestConfig requestConfig = RequestConfig.custom()
		        .setConnectTimeout(120000)
		        .setSocketTimeout(120000)//超时设置
		        .build();
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setRetryHandler(myRetryHandler)//重试设置
				.setDefaultRequestConfig(requestConfig)
				.build();
		return httpclient;
	}
	
	public static String get(String url) throws Exception {
		return get(url,null,null);
	}
		
	public static String get(String url,Map<String, String> header,Map<String, String> outCookies) throws Exception {
		String body = "";		
		String Encoding ="utf-8";		
		CloseableHttpClient client = createClient();
		try {
			CookieStore cookieStore = new BasicCookieStore();			
			HttpClientContext localContext = HttpClientContext.create();
			localContext.setCookieStore(cookieStore);
			// 创建get方式请求对象
			HttpGet httpGet = new HttpGet(url);
			if(header!=null){
				if(header.get("Accept")!=null) httpGet.setHeader("Accept", header.get("Accept"));
				if(header.get("Cookie")!=null) httpGet.setHeader("Cookie", header.get("Cookie"));
				if(header.get("Accept-Encoding")!=null) httpGet.setHeader("Accept-Encoding", header.get("Accept-Encoding"));
				if(header.get("Accept-Language")!=null) httpGet.setHeader("Accept-Language", header.get("Accept-Language"));
				if(header.get("Host")!=null) httpGet.setHeader("Host", header.get("Host"));
				if(header.get("User-Agent")!=null) httpGet.setHeader("User-Agent", header.get("User-Agent"));
				if(header.get("x-requested-with")!=null) httpGet.setHeader("x-requested-with", header.get("x-requested-with"));
				if(header.get("Encoding")!=null) Encoding =header.get("Encoding");
			}
			System.out.println("请求地址:" + url);
			// 执行请求操作,并拿到结果(同步阻塞)
			CloseableHttpResponse response = client.execute(httpGet,localContext);			
			// 获取结果实体
			try {
				// 如果需要输出cookie
				if(outCookies!=null){
					List<Cookie> cookies = cookieStore.getCookies();					
	                for (int i = 0; i < cookies.size(); i++) {
	                	outCookies.put(cookies.get(i).getName(),cookies.get(i).getValue());
	                }
				}
				HttpEntity entity = response.getEntity();
				System.out.println("返回:" + response.getStatusLine());
				if (entity != null) {
					// 按指定编码转换结果实体为String类型
					body = EntityUtils.toString(entity, Encoding);
					// System.out.println("返回:"+body);
				}
			} finally {
				response.close();
			}
		} finally {
			client.close();
		}
		return body;
	}

	public static String post(String url, Map<String, String> params)
			throws Exception {
		return post(url, params, null,null);
	}
	
	public static String post(String url, Map<String, String> params, Map<String, String> header,Map<String, String> outCookies)
			throws Exception {
		String body = "";
		String encoding ="utf-8";
		String contentType="text/html";
		CloseableHttpClient client = createClient();
		CookieStore cookieStore = new BasicCookieStore();			
		HttpClientContext localContext = HttpClientContext.create();
		localContext.setCookieStore(cookieStore);
		try {
			// 创建post方式请求对象
			HttpPost httpPost = new HttpPost(url);
			if(header!=null){
				if(header.get("Accept")!=null) httpPost.setHeader("Accept", header.get("Accept"));
				if(header.get("Cookie")!=null) httpPost.setHeader("Cookie", header.get("Cookie"));				
				if(header.get("Accept-Encoding")!=null) httpPost.setHeader("Accept-Encoding", header.get("Accept-Encoding"));
				if(header.get("Accept-Language")!=null) httpPost.setHeader("Accept-Language", header.get("Accept-Language"));
				if(header.get("Host")!=null) httpPost.setHeader("Host", header.get("Host"));
				if(header.get("User-Agent")!=null) httpPost.setHeader("User-Agent", header.get("User-Agent"));
				if(header.get("x-requested-with")!=null) httpPost.setHeader("x-requested-with", header.get("x-requested-with"));
				if(header.get("Encoding")!=null) encoding =header.get("Encoding");
				if(header.get("Content-Type")!=null) contentType =header.get("Content-Type");
			}
			// 装填参数
			if (contentType.equalsIgnoreCase("text/html")) {
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				if (params != null) {
					for (Entry<String, String> entry : params.entrySet()) {
						nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
					}
				}
				httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
			}
			//JOSN格式参数
			if (contentType.equalsIgnoreCase("application/json")) {
				StringEntity myEntity = new StringEntity(JSON.toJSONString(params.get("data")),
						ContentType.create("application/json", "UTF-8"));
				httpPost.setEntity(myEntity);
			}
			System.out.println("请求地址:" + url);
			// 执行请求操作,并拿到结果(同步阻塞)
			CloseableHttpResponse response = client.execute(httpPost,localContext);
			// 获取结果实体
			try {
				// 如果需要输出cookie
				if(outCookies!=null){
					List<Cookie> cookies = cookieStore.getCookies();					
	                for (int i = 0; i < cookies.size(); i++) {
	                	outCookies.put(cookies.get(i).getName(),cookies.get(i).getValue());
	                }
				}
				HttpEntity entity = response.getEntity();
				System.out.println("返回:" + response.getStatusLine());
				if (entity != null) {
					// 按指定编码转换结果实体为String类型
					body = EntityUtils.toString(entity, encoding);
					// System.out.println("返回:"+body);
				}
			} finally {
				response.close();
			}
		} finally {
			client.close();
		}
		return body;
	}
	public static void main(String[] args) throws Exception {
		String body =get("https://www.baidu.com/");
		System.out.println(body);
	}
}