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

主要是基于新版本HttpClient 4.5:

/**
解决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);
}
}

  

HttpClient4.5 SSL访问工具类的更多相关文章

  1. 基于HttpClient4.5.1实现Http访问工具类

    本工具类基于httpclient4.5.1实现 <dependency> <groupId>org.apache.httpcomponents</groupId> ...

  2. Java 实现Https访问工具类 跳过ssl证书验证

    不多BB ,代码直接粘贴可用 import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.F ...

  3. Spring---资源访问工具类

    JDK所提供的访问资源的类并不能很好的满足各种底层资源的访问需求,因此,Spring设计了一个Resource接口,它为应用提供了更强大的访问底层资源的能力 主要方法 boolean exists() ...

  4. 【JDBC】Java 连接 MySQL 基本过程以及封装数据库工具类

    一. 常用的JDBC API 1. DriverManager类 : 数据库管理类,用于管理一组JDBC驱动程序的基本服务.应用程序和数据库之间可以通过此类建立连接.常用的静态方法如下 static ...

  5. Java判断访问设备为手机、微信、PC工具类

    package com.lwj.util; import javax.servlet.http.HttpServletRequest; /** * 判断访问设备为PC或者手机--工具类 * * @de ...

  6. httpclient4.3 工具类

    httpclient4.3  java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...

  7. [C#] 常用工具类——应用程序属性信息访问类

    using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespac ...

  8. 一、JDBC的概述 二、通过JDBC实现对数据的CRUD操作 三、封装JDBC访问数据的工具类 四、通过JDBC实现登陆和注册 五、防止SQL注入

    一.JDBC的概述###<1>概念 JDBC:java database connection ,java数据库连接技术 是java内部提供的一套操作数据库的接口(面向接口编程),实现对数 ...

  9. 反射工具类.提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class,被AOP过的真实类等工具函数.java

    import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.ap ...

随机推荐

  1. linux screen 命令详解[转]

    一.背景 系统管理员经常需要SSH 或者telent 远程登录到Linux 服务器,经常运行一些需要很长时间才能完成的任务,比如系统备份.ftp 传输等等.通常情况下我们都是为每一个这样的任务开一个远 ...

  2. SQL SERVER同步环境新增发布对象时不能生成(sp_MS+表名)同步存储过程

    在配置了同步的用户环境(订阅端:请求订阅) 在发布端: 1.企业管理器SSMS—复制—本地发布—发布属性—项目(选中发布对象) 2.在企业管理里—查看快照代理状态(启动) 在订阅服务器: USE [D ...

  3. jasper 常用知识点总结

    1.应用: 列头 "YYYY-MM" 格式转化为 "MM YYYY"格式, eg : Date1 = 2014-11 new java.text.SimpleD ...

  4. Linux服务器开机没响应,BIOS信息都没有

    于2015-10-16,记得是4月份装的服务器,上边ineedle都部署完毕,当时没有派上用场,这次华为测试需要一台ineedle测试机,便把这个安装好的ineedle请出来了,插上电源后,接上网线, ...

  5. 002.ICMP--拼接ICMP包,实现简单Ping程序(原始套接字)

    一.大致流程: 将ICMP头和时间数据设置好后,通过创建好的原始套接字socket发出去.目的主机计算效验和后会将数据原样返回,用当前时间和返回的数据结算时间差,计算出rtt. 二.数据结构: ICM ...

  6. java 自动装箱自动拆箱

    1.Java数据类型 在介绍Java的自动装箱和拆箱之前,我们先来了解一下Java的基本数据类型. 在Java中,数据类型可以分为两大种,Primitive Type(基本类型)和Reference ...

  7. Hadoop2.6 datanode配置在线更新

    datanode 的配置可以在线更新了,http://blog.cloudera.com/blog/2015/05/new-in-cdh-5-4-how-swapping-of-hdfs-datano ...

  8. Interlocked系列函数线程同步的缺陷

    1. Code int Work() { while (m_lInterlockedData < 10) { InterlockedIncrement(&m_lInterlockedDa ...

  9. nodejs入门

    一.Nodejs介绍 简单的说 Node.js 就是运行在服务端的 JavaScript的代码解析器. 首先要清楚Node不是一个Web服务器,这十分重要.它本身并不能做任何事情.它无法像Apache ...

  10. MMORPG大型游戏设计与开发(客户端架构 part10 of vegine)

    界面是游戏中必不可少的一部分,就算你进入游戏没有看到什么UI窗口,你也不必着急,因为多多少少都会有隐藏着的界面等你去体验.一个好的UI大部分应该归功于设计的人与提供美术支持的人员,因为他们是直接设计U ...