HttpClient4.5 SSL访问工具类
要从网上找一个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访问工具类的更多相关文章
- 基于HttpClient4.5.1实现Http访问工具类
本工具类基于httpclient4.5.1实现 <dependency> <groupId>org.apache.httpcomponents</groupId> ...
- Java 实现Https访问工具类 跳过ssl证书验证
不多BB ,代码直接粘贴可用 import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.F ...
- Spring---资源访问工具类
JDK所提供的访问资源的类并不能很好的满足各种底层资源的访问需求,因此,Spring设计了一个Resource接口,它为应用提供了更强大的访问底层资源的能力 主要方法 boolean exists() ...
- 【JDBC】Java 连接 MySQL 基本过程以及封装数据库工具类
一. 常用的JDBC API 1. DriverManager类 : 数据库管理类,用于管理一组JDBC驱动程序的基本服务.应用程序和数据库之间可以通过此类建立连接.常用的静态方法如下 static ...
- Java判断访问设备为手机、微信、PC工具类
package com.lwj.util; import javax.servlet.http.HttpServletRequest; /** * 判断访问设备为PC或者手机--工具类 * * @de ...
- httpclient4.3 工具类
httpclient4.3 java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...
- [C#] 常用工具类——应用程序属性信息访问类
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespac ...
- 一、JDBC的概述 二、通过JDBC实现对数据的CRUD操作 三、封装JDBC访问数据的工具类 四、通过JDBC实现登陆和注册 五、防止SQL注入
一.JDBC的概述###<1>概念 JDBC:java database connection ,java数据库连接技术 是java内部提供的一套操作数据库的接口(面向接口编程),实现对数 ...
- 反射工具类.提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class,被AOP过的真实类等工具函数.java
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.ap ...
随机推荐
- SQLHelp帮助类
public readonly static string connStr = ConfigurationManager.ConnectionStrings["conn"].Con ...
- PostgreSQL-安装9.2
一.环境 VM虚拟机 NAME="Ubuntu" VERSION="12.04.4 LTS, Precise Pangolin" 二.过程 1.安装make ...
- Java的String.valueOf 转换 与、空串+类型变量转换与封装类(Integer)的toString方式转换比较。
1.空串+类型变量方式转换 int i=20; String s=""+i; 这种方式实际上经过了两个步骤,首先进行了i.ToString()把 i 转换为 字符串,然后再进行加法 ...
- x01.os.16: 添加功能
准备工作 1.确保是 win xp,如是 win 8,运行 nasm 需按提示同意安装组件. 2.确保 src 和 z_tools 在同一目录下,nasm 已包含在 z_tools 文件夹中. ...
- Linux rpm 查询
[root@wang /]# rpm -qa // 查看安装所有包 [root@wang /]# rpm -qa |grep vim // 查询所安装的包 +包名 [root@wang /]# rpm ...
- Python使用QRCode模块生成二维码
QRCode官网https://pypi.python.org/pypi/qrcode/5.1 简介python-qrcode是个用来生成二维码图片的第三方模块,依赖于 PIL 模块和 qrcode ...
- hw 要的是螺丝钉
日前突然接到华为HR的电话,叫我去面试。本来我的工作和工资收入等各方面在本地也还算可以,没有想要跳槽。但是本着去看看有没有更好机会的想法就去了。 9:30到了现场后,在那里等了很久,一个考官上来问了 ...
- setTimeout()与setInterval()——走马灯效果
JavaScript中的setTimeout()与setInterval()都是指延时执行某一操作. 但setInterval()指每隔指定时间执行某操作,会循环不断地执行该操作:setTimeout ...
- [转]Oracle 修改或者删除临时表 ORA-14452: 试图创建, 更改或删除正在使用的临时表中的索引
本文转自:http://blog.csdn.net/treasurelifelhf/article/details/7290729 由于存储过程出现问题,导致前台页面无法显示数据.执行存储过程发现临时 ...
- [转]jQuery: how to get which button was clicked upon form submission?
本文转自:http://stackoverflow.com/questions/5721724/jquery-how-to-get-which-button-was-clicked-upon-form ...