要从网上找一个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. pom.xml 样例

    <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven ...

  2. gulp系列:简单实践

    coffescript测试源码   gulp = require('gulp') #删除 1.清空目录 常用插件 gulp-clean .del (nodejs模块) del = require('d ...

  3. 为IIS站点添加限制IP

    /// <summary> /// 添加站点限制IP /// </summary> /// <param name="sitename">站点名 ...

  4. 设计模式C#实现(十二)——装饰模式

    意图 0 适用性 1 结构 2 实现 3 效果 4 参考 5 意图 动态的给一个对象添加一些额外的职责. 适用性 动态的为单个对象添加职责而不影响其他对象 处理那些可以撤销的职责(? 在某些功能不需要 ...

  5. Windows Sever关于80端口之争

    默认情况下安装了IIS服务器角色的Windows系统,其80端口就被占用了.但是占用80端口的进程却不是WWW Service更不是IIS Admin Sevice,而是处于kernel地位的Http ...

  6. android ListView 和 BaseAdapter 应用

    步聚: 1.建立ListView对象:--(作用:绑定Adapter呈现数据) 2.建立ListView实现的Item栏位.xml布局:--(作用:实现ListView的栏位布局) 3.建立Item. ...

  7. Java基础语法总结1

    一.标识符及字符集 Java语言规定标识符是以字母.下划线"_"或美元符号"$"开始,随后可跟数字.字母.下划线或美元符号的字符序列.Java标识符大小写敏感, ...

  8. Android,LIstView中的OnItemClick点击无效的解决办法

    在List_Item布局文件中的根节点加上如下背景标黄的这一行 <?xml version="1.0" encoding="utf-8"?> < ...

  9. C++浅析——虚函数的动态和静态绑定

    源自一道面试题,觉得很有意思 class CBase { public: virtual void PrintData(int nData = 111); }; void CBase::PrintDa ...

  10. POJ3967Ideal Path[反向bfs 层次图]

    Ideal Path Time Limit: 10000MS   Memory Limit: 65536K Total Submissions: 1754   Accepted: 240 Descri ...