轻松把玩HttpClient之配置ssl,采用设置信任自签名证书实现https

简介: 在上篇文章《HttpClient配置ssl实现https简单示例——绕过证书验证》中简单分享了一下如何绕过证书验证。如果你想用httpclient访问一个网站,但是对方的证书没有通过ca认证或者其他问题导致证书不被信任,比如12306的证书就是这样的。

在上篇文章《HttpClient配置ssl实现https简单示例——绕过证书验证》中简单分享了一下如何绕过证书验证。如果你想用httpclient访问一个网站,但是对方的证书没有通过ca认证或者其他问题导致证书不被信任,比如12306的证书就是这样的。所以对于这样的情况,你只能是选择绕过证书验证的方案了。

但是,如果是自己用jdk或者其他工具生成的证书,还是希望用其他方式认证自签名的证书,这篇文章就来分享一下如何设置信任自签名的证书。当然你也可以参考官网示例中。

要想信任自签名的证书,必须得知道密钥库的路径及密钥库的密码。然后加载到程序来才可以。具体代码如下:

	/**
	 * 设置信任自签名证书
	 * 	
	 * @param keyStorePath		密钥库路径
	 * @param keyStorepass		密钥库密码
	 * @return
	 */
	public static SSLContext custom(String keyStorePath, String keyStorepass){
		SSLContext sc = null;
		FileInputStream instream = null;
		KeyStore trustStore = null;
		try {
			trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			instream = new FileInputStream(new File(keyStorePath));
			trustStore.load(instream, keyStorepass.toCharArray());
			// 相信自己的CA和所有自签名的证书
			sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
		} catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) {
			e.printStackTrace();
		} finally {
			try {
				instream.close();
			} catch (IOException e) {
			}
		}
		return sc;
	}
然后修改原来的send方法:
	/**
	 * 模拟请求
	 * 
	 * @param url		资源地址
	 * @param map	参数列表
	 * @param encoding	编码
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws KeyManagementException 
	 * @throws NoSuchAlgorithmException 
	 * @throws ClientProtocolException 
	 */
	public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException {
		String body = "";
		
		//tomcat是我自己的密钥库的密码,你可以替换成自己的
		//如果密码为空,则用"nopassword"代替
		SSLContext sslcontext = custom("D:\\keys\\wsriakey", "tomcat");
		
        // 设置协议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();
		
		//创建post方式请求对象
		HttpPost httpPost = new HttpPost(url);
		
		//装填参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if(map!=null){
			for (Entry<String, String> entry : map.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		//设置参数到请求对象中
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

		System.out.println("请求地址:"+url);
		System.out.println("请求参数:"+nvps.toString());
		
		//设置header信息
		//指定报文头【Content-type】、【User-Agent】
		httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
		httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		
		//执行请求操作,并拿到结果(同步阻塞)
		CloseableHttpResponse response = client.execute(httpPost);
		//获取结果实体
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			//按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, encoding);
		}
		EntityUtils.consume(entity);
		//释放链接
		response.close();
        return body;
	}
测试一下吧:
	public static void main(String[] args) throws ParseException, IOException, KeyManagementException, NoSuchAlgorithmException{
		String url = "https://sso.tgb.com:8443/cas/login";
		String body = send(url, null, "utf-8");
		System.out.println("交易响应结果长度:"+body.length());
		
		System.out.println("-----------------------------------");
		
		url = "https://kyfw.12306.cn/otn/";
		body = send(url, null, "utf-8");
		System.out.println("交易响应结果长度:"+body.length());
	}
测试结果:



从结果中,我们很清楚的看到,使用自签名的证书,访问自签名的网站可以正常访问,访问12306则会失败。所以自签名的也只能用于自定义密钥和证书的情况下使用。而12306这种情况还是要用上一篇提到的“绕过证书验证”方案。

目录
相关文章
|
1月前
|
前端开发
webpack如何设置devServer启动项目为https协议
webpack如何设置devServer启动项目为https协议
141 0
|
2月前
|
前端开发 应用服务中间件 Linux
nginx解决springcloud前后端跨域问题,同时配置ssl
nginx解决springcloud前后端跨域问题,同时配置ssl
|
4天前
|
安全 应用服务中间件 网络安全
SSL原理、生成SSL密钥对、Nginx配置SSL
现在,你的Nginx虚拟主机应该已经配置了SSL,可以通过HTTPS安全访问。确保在生产环境中使用有效的SSL证书来保护通信的安全性。
16 0
|
17天前
|
域名解析 网络协议 应用服务中间件
阿里云SSL证书配置(HTTPS证书配置)
该内容是一个关于如何在阿里云上准备和购买SSL证书,以及如何为网站启用HTTPS的步骤指南。首先,需要注册并实名认证阿里云账号,然后在SSL证书控制台选择证书类型、品牌和时长进行购买。申请证书时填写域名信息,并进行DNS验证,这包括在阿里云域名管理板块添加解析记录。完成验证后提交审核,等待证书审核通过并下载Nginx格式的证书文件。最后,将证书配置到网站服务器以启用HTTPS。整个过程涉及账户注册、实名认证、证书购买、DNS设置和证书下载及安装。
87 0
|
29天前
|
前端开发 应用服务中间件 网络安全
http转为https,ssl证书安装及nginx配置
http转为https,ssl证书安装及nginx配置
47 1
|
1月前
|
存储 缓存 安全
https跳过SSL认证时是不是就是不加密的,相当于http?
https跳过SSL认证时是不是就是不加密的,相当于http?
123 0
|
1月前
|
弹性计算 网络安全 Apache
windows server2012服务器下PHPstudy配置ssl证书(https配置)
windows server2012服务器下PHPstudy配置ssl证书(https配置)
70 0
|
2月前
|
DataWorks 关系型数据库 Shell
DataWorks数据源问题之配置ssl加密如何解决
DataWorks数据源是指DataWorks中配置的用于数据集成的外部数据源;本合集将讲解如何在DataWorks中配置和管理数据源,以及处理数据源连接和集成过程中的问题。
50 5
|
网络安全 Apache 开发工具
实现HTTPS(Apache+OpenSSL)
https,全称 hypertext transfer protocol secure,安全的超文本传输协议 广泛应用于万维网上安全敏感的通讯
275 0
|
3月前
|
Web App开发 移动开发 JavaScript
Python网络编程(三),HTTP协议
Python网络编程(三),HTTP协议
61 0