如何使用HttpClient来发送带客户端证书的请求,以及如何忽略掉对服务器端证书的校验
最近要做客户端和服务器端的双向认证,在客户端向服务器端发送带证书的请求这里有一点问题,网上的例子大多都不太好使,于是找了github上httpclient源代码中的例子改造了一下,终于弄明白了
github上我参考的例子在:https://github.com/apache/httpclient/blob/4.5.x/httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java
下面先贴上我自己的代码(需要导入HttpClient等相关jar包),然后再说明
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; /*
* Created with Intellij IDEA
* USER: 焦一平
* Date: 2016/5/8
* Time: 1:10
* To change this template use File | Settings | File Template
*/
public class SSLDemo {
public static void main(String[] args) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\jiaoyiping.p12")), "123456".toCharArray());
SSLContext sslcontext = SSLContexts.custom()
//忽略掉对服务器端证书的校验
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}) //加载服务端提供的truststore(如果服务器提供truststore的话就不用忽略对服务器端证书的校验了)
//.loadTrustMaterial(new File("D:\\truststore.jks"), "123456".toCharArray(),
// new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, "cmcc".toCharArray())
.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build(); try { HttpGet httpget = new HttpGet("https://10.2.5.116/PnsReceiver/ReceiveMessage"); System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
System.out.println(IOUtils.toString(entity.getContent()));
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
SSLContexts.custom() 方法返回一个 SSLContextBuilder实例,来构建SSLContext,下面是SSLContextBuilder的方法列表:
其中:
loadKeyMaterial()重载方法是加载客户端证书用的
loadTrustMaterial()重载方法是加载服务器端相关信息用的(我们就是使用 loadTrustMaterial(TrustStrategy trustStrategy) 方法自己实现了一个信任策略,不对服务器端的证书进行校验), 在生成HttpClient的时候,指定相应的 SSLSocketFactory,之后,使用这个HttpClient发送的GET请求和POST请求就自动地附加上了证书信息 如果我们只需要忽略掉对服务器端证书的验证,而不需要发送客户端证书信息,在构建SSLContext的时候,只需要 loadTrustMaterial() 不需要 loadKeyMaterial() 关于客户端证书的类型问题:我们导出的pfx或者P12后缀的文件都是pkcs12类型的,根据java的文档,我找到了KeyStore支持的三种类型,如下图:
客户端如何只信任某个服务器端的证书信息 会在之后的文章中写
如何使用HttpClient来发送带客户端证书的请求,以及如何忽略掉对服务器端证书的校验的更多相关文章
- postman发送带cookie的http请求
1:需求:测试接口的访问权限,对于某些接口A可以访问,B不能访问. 2:问题:对于get请求很简单,登录之后,直接使用浏览器访问就可以: 对于post请求的怎么测试呢?前提是需要登录态,才能访问接口. ...
- requests模块发送带headers的Get请求和带参数的请求
1.在PyCharm开发工具中新建try_params.py文件: 2.try_params.py文件中编写代码: import requests#设置请求Headers头部header = {&qu ...
- ASP.NET 截获服务器生成的将要发送到客户端的html的方法
有时候我们需要在将服务器端生成的html发送带客户端之前对这些html进行操作,比如生成静态html加之保存.改变生成的html中的某些内容等等,那么久可以通过如下的方案解决. 我总结了两种方式,个人 ...
- nodejs 如何发送一个带JSON的GET请求?
GET /megacorp/employee/_search { "aggs" : { "all_interests" : { "terms" ...
- 使用Spring发送带附件的电子邮件(站内和站外传送)
JavaMail的介绍 JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口.它是Sun发布的用来处理email的API.它可以方便地执行一些常用的邮件传输. 虽然JavaMail是 ...
- httpclient的get带参不带参post带参不带参的简单应用
一,基础的的应用 1.1,get的无参请求 @Test public void doGet() throws Exception { //创建一个httpclient对象 CloseableHttpC ...
- ORACLE发送带附件邮件的二三事之一
在oracle使用过程中,我们可以通过pl/sql生成数据文件,也可以通过spool on spool off生成,但某些环境下,我们需要通过存储过程处理数据,数据处理完,需要自动生成数据文件,手工导 ...
- 从零开始学习Node.js例子七 发送HTTP客户端请求并显示响应结果
wget.js:发送HTTP客户端请求并显示响应的各种结果 options对象描述了将要发出的请求.data事件在数据到达时被触发,error事件在发生错误时被触发.HTTP请求中的数据格式通过MIM ...
- JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求
JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求 哇,一看标题怎么这么长啊,其实意思很简单,哥讨厌用HTTP Client做POST与GET提交 觉得那个毕竟是别人写 ...
随机推荐
- lakala proportion轨迹分析代码
/** * Created by lkl on 2017/12/7. */ import breeze.numerics.abs import org.apache.spark.sql.SQLCont ...
- css实现图片横向排列滚动
.imageList{ overflow-x: auto; overflow-y: hidden; height:180px; white-space: nowrap; img{ width:auto ...
- 常用的网络上的Webservice接口
商业和贸易: 1.股票行情数据 WEB 服务(支持香港.深圳.上海基金.债券和股票:支持多股票同时查询) Endpoint: http://webservice.webxml.com.cn/WebSe ...
- QT编译错误:Project ERROR: This example requires Qt to be configured with -opengl desktop
学习QT场景视图,对一个Boxes的例子比较感兴趣,于是去编译学习,结果编译不能通过(使用的是QT5.12): Project ERROR: This example requires Qt to b ...
- Python爬虫-爬取科比职业生涯高清图集
前面学习了Python爬取豆瓣电影Top250的数据,爬取的信息是电影信息的文本信息,但是在互联网上流行的图片才有更大的吸引力,本篇我们来使用python爬取网页上的图片并保存在本地硬盘上,很兴奋吧, ...
- 18个不常见的C#关键字,您使用过几个?
转自:http://www.cnblogs.com/zhuqil/archive/2010/04/09/UnCommon-Csharp-keywords-A-Look.html 1.__arglist ...
- c 编译和链接过程
详解link 有 些人写C/C++(以下假定为C++)程序,对unresolved external link或者duplicated external simbol的错误信息不知所措(因为这样的错 ...
- mybatis generator配置,Mybatis自动生成文件配置,Mybatis自动生成实体Bean配置
mybatis generator配置,Mybatis自动生成文件配置,Mybatis自动生成实体Bean配置 ============================== 蕃薯耀 2018年3月14 ...
- 【NLP】HanLP环境
1.参考:https://github.com/hankcs/pyhanlp 2.问题: C:\Users\ADMINI~1\AppData\Local\Temp\pip-install-u617cf ...
- RF-获取上个月份
验证1: case ${NowDate} set variable 20170103 ${year} set variable ${NowDate[0:4]} ${month} set variabl ...