HttpClient配置SSL绕过https证书
https://blog.csdn.net/irokay/article/details/78801307
HttpClient简介
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。更多信息请关注http://hc.apache.org/
请求步骤
许多需要后台模拟请求的系统或者框架都用的是httpclient,使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:
- 创建CloseableHttpClient对象。
- 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
- 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
- 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
- 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
- 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
- 释放连接。无论执行方法是否成功,都必须释放连接
先看个官方HttpClient通过Http协议发送get请求,请求网页内容的例子:
1.ClientWithResponseHandler.java
/*
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.client;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* This example demonstrates the use of the {@link ResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated resources.
*/
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} finally {
httpclient.close();
}
}
}
我把上述例子中的请求地址改为了“http://www.baidu.com/”,运行后控制台可以获取百度首页网页内容:
下面把地址改为https地址:https://www.baidu.com/,再次尝试运行:
报错了,提示unable to find valid certification path to requested target,无法通过htpps认证。
正规途径,我们需要将证书导入到密钥库中,现在我们采取另外一种方式:绕过https证书认证实现访问。
2.Method SSLContext
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
修改1中main方法:
public final static void main(String[] args) throws Exception {
String body = "";
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
//设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//CloseableHttpClient client = HttpClients.createDefault();
try{
//创建get方式请求对象
HttpGet get = new HttpGet("https://www.baidu.com/");
//指定报文头Content-type、User-Agent
get.setHeader("Content-type", "application/x-www-form-urlencoded");
get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(get);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
//释放链接
response.close();
System.out.println("body:" + body);
} finally{
client.close();
}
}
运行代码,获取网页内容成功!
同理,再尝试下post请求:
public final static void main(String[] args) throws Exception {
String body = "";
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
//设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//CloseableHttpClient client = HttpClients.createDefault();
try{
//创建post方式请求对象
HttpPost httpPost = new HttpPost("https://api.douban.com/v2/book/1220562");
//指定报文头Content-type、User-Agent
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
//释放链接
response.close();
System.out.println("body:" + body);
}finally{
client.close();
}
}
https地址以豆瓣的一个api为例,获得ID为1220562的书的信息。
运行代码:
获取返回信息成功。
本博客例子下载地址:
http://download.csdn.net/download/irokay/10158259
例子中包含以上工程代码,以及所需HttpClient组件jar库。
参考:
https://www.cnblogs.com/ITtangtang/p/3968093.html
http://blog.csdn.net/xiaoxian8023/article/details/49865335
https://www.cnblogs.com/ITtangtang/p/3968093.html
HttpClient配置SSL绕过https证书的更多相关文章
- Windows下Nginx配置SSL实现Https访问(包含证书生成)
Vincent.李 Windows下Nginx配置SSL实现Https访问(包含证书生成) Windows下Nginx配置SSL实现Https访问(包含证书生成) 首先要说明为什么要实现https ...
- Java.HttpClient绕过Https证书解决方案二
方案2 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.security.Secur ...
- Java.HttpClient绕过Https证书解决方案一
方案1 import javax.net.ssl.*; import java.io.*; import java.net.URL; import java.security.KeyManagemen ...
- php 品牌全车零件订购平台( 带采集数据 及 账号自动登陆【已绕过https证书加密】,php源码 ,QQ: 876635409 )
php捷豹路虎 品牌全车零件订购平台 ( 带采集数据 及 账号自动登陆[已绕过https证书加密],php源码 ,QQ: 876635409 [由于咨询用户太多,请备注:汽车配件]) 一.php+m ...
- Centos7.2下Nginx配置SSL支持https访问(站点是基于.Net Core2.0开发的WebApi)
准备工作 1.基于nginx部署好的站点(本文站点是基于.Net Core2.0开发的WebApi,有兴趣的同学可以跳http://www.cnblogs.com/GreedyL/p/7422796. ...
- springboot配置SSL自签名证书
1.证书生成 每一个JDK或者JRE里都有一个工具,叫做:keytool,安装了jdk或jre之后,配置好JAVA环境之后,就可以直接在控制台使用该命令生成自签名证书: 在控制台输入: keytool ...
- Springboot 配置 ssl 实现HTTPS 请求 & Tomcat配置SSL支持https请求
SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议.TLS与 ...
- Weblogic配置SSl使用Https
一 .可以开启自带的SSL连接 启动weblogic,进入左侧菜单,点击左侧的安全领域-->点击myrealm-->点击角色和策略-->点击服务器AdminServer 点击保存,w ...
- Springboot配置ssl使用https
SSL(Secure Sockets Layer 安全套接层)是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络连接进行加密,SSL协议位于TCP/IP协议与各种应用层协议之间, ...
随机推荐
- thinkphp---模糊查询详解
最近做项目,在做搜索模块的时候,模糊查询肯定少不了. 今天就详细的看一下模糊查询: $where['title'] = array('like','%'.$words.'%'); $where['ti ...
- ubuntu部署nginx
先更新本机内置的程序. sudo apt-get updatesudo apt-get upgrade再判断系统是否内置了add-apt-repository命令,如果没有执行下列命令安装 sudo ...
- java虚拟机的符号引用和直接引用
在java中,一个java类将会编译成一个class文件.在编译时,java类并不知道引用类的实际内存地址,因此只能使用符号引用来代替.比如org.simple.People类引用org.simple ...
- HDU 1542 - Atlantis - [线段树+扫描线]
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1542 Time Limit: 2000/1000 MS (Java/Others) Memory Li ...
- 关于matlab小记
目录: 1.函数取整 2.数据显示格式 3.三角函数运算 4.矩阵运算 5.函数句柄 6.二维函数图像绘制 7.符号对象 8.关于微积分 9.关于逻辑语句 10.关于运算符 ───────────── ...
- POJ 1849 - Two - [DFS][树形DP]
Time Limit: 1000MS Memory Limit: 30000K Description The city consists of intersections and streets t ...
- SQL Fundamentals: 子查询 || 行列转换(PIVOT,UNPIVOT,DECODE),设置数据层次(LEVEL...CONNECT BY)
SQL Fundamentals || Oracle SQL语言 子查询(基础) 1.认识子查询 2.WHERE子句中使用子查询 3.在HAVING子句中使用子查询 4.在FROM子句中使用子查询 5 ...
- 数据结构——栈(C语言实现)
#include <stdio.h> #include <stdlib.h> #include<string.h> #include<malloc.h> ...
- flask_SQLAlchemy常用数据类型及列选项
SQLAlchemy常用数据类型:1. Integer:整形,映射到数据库中是int类型.2. Float:浮点类型,映射到数据库中是float类型.他占据的32位.3. Double:双精度浮点类型 ...
- DLL远程注入及卸载实现
实现win7 64位系统下dll的远程注入及卸载,尚未再其他系统测试 源码地址:https://github.com/ndhisrfzs/InjectDll