要从网上找一个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. mysql-mmm 安装配置(双主)

    原文地址:mysql-mmm 安装配置 作者:chinaunix1116 MMM即Master-Master Replication Managerfor MySQL(mysql主主复制管理器)关于m ...

  2. Python运算符,python入门到精通[五]

    运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算.例如:2+3,其操作数是2和3,而运算符则是“+”.在计算器语言中运算符大致可以分为5种类型:算术运算符.连接运算符.关系运算符.赋值运 ...

  3. sed grep find命令

    一.sed [-nerf][n1,n2] action -n 安静模式,只有经过sed处理过的行才显示出来,其他不显示. -r 表示sed支持扩展的正则表达式 -e 表示直接在命令行模式上进行sed操 ...

  4. libsvm Minist Hog 手写体识别

    统计手写数字集的HOG特征 转载请注明出处,楼燚(yì)航的blog,http://www.cnblogs.com/louyihang-loves-baiyan/ 这篇文章是模式识别的小作业,利用sv ...

  5. C#迭代重载等

    迭代器 迭代器是作为一个容器,将要遍历的数据放入,通过统一的接口返回相同类型的值 迭代器代码使用 yield return 语句依次返回每个元素.yield break 将终止迭代 类中实现多个迭代器 ...

  6. Codeforces Round #282 Div.1 B Obsessive String --DP

    题意: 给两个串S,T,问能找出多少的S的(a1,b1)(a2,b2)..(ak,bk),使Sa1---Sb1,...Sak---Sbk都包含子串T,其中k>=1,且(a1,b1)...(ak, ...

  7. AC日记——求10000以内n的阶乘 openjudge 1.6 14

    14:求10000以内n的阶乘 总时间限制:  5000ms 内存限制:  655360kB 描述 求10000以内n的阶乘. 输入 只有一行输入,整数n(0<=n<=10000). 输出 ...

  8. JAVA 字符串驻留池

    一切从String str = new String("abc")说起...    这行代码形式上很简单,其实很复杂.有一个常见的Java笔试题就是问上面这行代码创建了几个Stri ...

  9. QuickFix/N简介

    QuickFix/N简介  FIX是Financial Information eXchange的简称.FIX是一种专门为实时电子证券交易设计的标准消息协议.该协议由FIX protocol, Ltd ...

  10. redis存在大量脏页问题的追查记录

    from:https://www.zybuluo.com/SailorXiao/note/136014 case现场 线上发现一台机器内存负载很重,top后发现一个redis进程占了大量的内存,TOP ...