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 ...
随机推荐
- coursera机器学习笔记-多元线性回归,normal equation
#对coursera上Andrew Ng老师开的机器学习课程的笔记和心得: #注:此笔记是我自己认为本节课里比较重要.难理解或容易忘记的内容并做了些补充,并非是课堂详细笔记和要点: #标记为<补 ...
- Vim指令备忘
从网上找来的记忆图,适合于刚上手的童鞋形象记忆. 接下来的是个人在使用过程中容易忘记的命令,特此备份查看. n<space> 会向右移动这一行的n 个字元 n<Enter> 向 ...
- 使用DBI(perl)实现文本文件的导入导出mysql
DBI 是perl脚本连接数据库的一个模块.perl脚本相对shell更灵活,功能更强大,跨平台能力强.相对可执行jar包要简单很多. 1.下载安装包DBI-1.631.tar.gzperl脚本下载 ...
- [嵌入式开发入门]4412开发板从零建立Linux最小系统
本文转自iTOP-4412开发板实战教程书籍 http://www.topeetboard.com iTOP-4412开发板不仅可以运行Android,还可以运行简单的Linux最小文件系统. 最小L ...
- 记一次ganglia的故障分析 mem_report不显示
ganglia集群中mem_report不能正确显示,有的显示有些不显示. 我通过web开发工具F12,获取生成图片的路径,然后加上&debug=3 显示发现: No matching met ...
- 学习OpenStack之 (3):Devstack Screen 使用技巧
Devstack环境中,openstack运行在一个screen中,每个service运行在一个window中.我总结的几个tips: 0. 注意需要使用screen启动用户来进行一下操作 1. 查看 ...
- Codeforces Round #371 (Div. 2) C. Sonya and Queries[Map|二进制]
C. Sonya and Queries time limit per test 1 second memory limit per test 256 megabytes input standard ...
- POJ2184 Cow Exhibition[DP 状态负值]
Cow Exhibition Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 12420 Accepted: 4964 D ...
- UWP数据绑定
[ 已针对 Windows 10 上的 UWP 应用更新. 有关 Windows 8.x 文章,请参阅存档 ] 数据绑定是你的应用 UI 用来显示数据的一种方法,可以选择与该数据保持同步. 借助数据绑 ...
- vijos[1355]车队过桥问题
描述 现有N辆车要按顺序通过一个单向的小桥,由于小桥太窄,不能有两辆车并排通过.另外,由于小桥建造的时间已经很久,只能承受有限的重量,记为Max(吨).管理员将N辆车按初始的顺序分组,每次让一个组过桥 ...