可以参考: 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();
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
我把上述例子中的请求地址改为了“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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
修改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();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
运行代码,获取网页内容成功!

同理,再尝试下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();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
---------------------
作者:irokay
来源:CSDN
原文:https://blog.csdn.net/irokay/article/details/78801307
版权声明:本文为博主原创文章,转载请附上博文链接!

[转]用代码访问 Https的更多相关文章

  1. c#代码访问https服务器以及https的webservice

    代码访问https类似浏览器操作 1.验证证书 2.如果要求客户端证书,提供客户端证书 具体代码如下: 访问https的web public static void ProcessRequest() ...

  2. 转 c#代码访问https服务器以及https的webservice

    最近公司做到WebService项目,但是要通过Https调用,自己在网上搜了半天,终于实现了服务端的Https,但是一直没有找到客户端如何实现,今天终于看到这篇文章,随手记录下来. 具体代码如下: ...

  3. HTTP-java访问https资源时,忽略证书信任问题,代码栗子

    java程序在访问https资源时,出现报错 sun.security.validator.ValidatorException: PKIX path building failed: sun.sec ...

  4. AFNetworking 原作者都无法解决的问题: 如何使用ip直接访问https网站?

    背景 最近App似乎有报异常是DNS无法解析,尝试解决此问题.搜集到的资料很少,甚至连AFN原作者都判定这可能是一个无解的问题,参见: https://github.com/AFNetworking/ ...

  5. [PHP] curl访问https与CA证书问题

    CA证书,用来在调用HTTPS资源的时候,验证对方网站是否是CA颁布的证书,而不是自己随便生成的 curl命令1.需要下载CA证书 文件地址是 http://curl.haxx.se/ca/cacer ...

  6. c# 中HttpClient访问Https网站

    c# 中HttpClient访问Https网站,加入如下代码: handler = new HttpClientHandler() ;handler.AllowAutoRedirect = true; ...

  7. 解决访问HTTPS,抛出的异常javax.net.ssl.SSLHandshakeException

    本地测试没问题,http换成https抛出异常javax.net.ssl.SSLHandshakeException,网上有说是服务器证书,有说要启动SSL3协议的,反正没有找到有用的. 在GET和P ...

  8. 如何访问https的网站?-【httpclient】

    备注:本处代码使用groovy和httpclient4.3作为例子进行讲述 在普通方式下,当使用httpclient进行访问某个网站时,大致使用如下的代码进行访问: CloseableHttpClie ...

  9. IIS7配置HTTPS+默认访问https路径

    一.下载证书(这里我使用的是阿里云免费的证书) 文件说明: 1. 1532858285913.key(证书私钥文件).1532858285913.pem(证书文件).1532858285913.pfx ...

随机推荐

  1. 案例:selenium实现登录处理弹窗

    func.py https://www.cnblogs.com/andy9468/p/10899508.html main.py中 # 导入webdriver import os import tim ...

  2. C#基础 结构体、枚举

    一 结构体 结构体(struct)指的是一种数据结构,一个变量组,是一个自定义的集合.通常使用结构体创造新的“属性”,封装一些属性来组成新的类型.   结构体一般定义在Mian函数上面,位于Class ...

  3. COM_STMT_PREPARE 1

    mysqld_stmt_prepare void mysqld_stmt_prepare(THD* thd, const char * query, uint length, Prepared_sta ...

  4. 用python实现新词发现程序——基于凝固度和自由度

    互联网时代,信息产生的数量和传递的速度非常快,语言文字也不断变化更新,新词层出不穷.一个好的新词发现程序对做NLP(自然预言处理)来说是非常重要的. N-Gram加词频 最原始的新词算法莫过于n-gr ...

  5. CF802C Heidi and Library (hard) 最小费用流

    你有一个容量为k的空书架,现在共有n个请求,每个请求给定一本书ai,如果你的书架里没有这本书,你就必须以ci的价格购买这本书放入书架. 当然,你可以在任何时候丢掉书架里的某本书.请求出完成这n个请求所 ...

  6. python+mysql:实现一千万条数据插入数据库

    作业要求 构建一个关系模式和课本中的关系movies(title,year,length,movietype,studioname,producerC)一样的关系,名称自定,在这个关系中插入1000万 ...

  7. Week08_day01 (Hive开窗函数 row_number()的使用 (求出所有薪水前两名的部门))

    数据准备: 7369,SMITH,CLERK,7902,1980-12-17,800,null,20 7499,ALLEN,SALESMAN,7698,1981-02-20,1600,300,30 7 ...

  8. Http协议与TCP协议

    背景 在日常工作中,经常会遇到某某框架是基于Http协议或者TCP协议,今天,就针对于该协议,整理下 从本质上来说,Http协议与TCP协议是应用在不同网络层,Http协议处于应用层,TCP处于传输层 ...

  9. iar8.32版本关于cmsis的说明

    平台是cubemx5.3 keil5.26 带freertos,使用iar8.32,在上图中的use cmsis 打勾与否都能编译通过.

  10. mongod破解版的安装

    navicat for mongodb 12,又叫做navicat 12 for mongodb,是针对mongodb软件而开发的一款管理软件,拥有高效图形用户界面,能够连接本地或远程的MongoDB ...