HttpClient实现HTTPS客户端编程---可信证书与自签名证书

本文介绍如何使用HttpClient处理HTTPS请求,包括访问可信证书和自签名证书的网站。讨论了证书校验、自签名证书导入、AlternativeName匹配问题及ConnectionManager的配置。并提供了完整的代码示例。
摘要由CSDN通过智能技术生成

HttpClient的HTTPS客户端编程—可信证书与自签名证书

本文基于HttpClient4.5.4,对可信证书和自签名证书的网站访问编码,涉及https连接过程、证书、证书链、根证书、keystore、自签名等概念,就不在本文中细说了。


简介

前世今生

网上能搜到httpclient使用的各种写法,基本是由于版本更迭导致的,前期为Apache Commons HttpClient,现在是Apache HttpComponents,从4.3.x版本开始类名和调用方式相较早期版本有了明显变化,下文中所有代码基于当前最新的4.5.4版本。

The Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules, which offer better performance and more flexibility. ——[来自官网]

如何引入

<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.4</version>
    </dependency>
</dependencies>

如何发送HTTPS请求

package org.fst.network;

import org.apache.http.client.methods.CloseableHttpResponse;
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;

public class HttpGetTest {
    public static void main(String[] args) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet("http://www.baidu.com");
            System.out.println("Executing request " + httpGet.getRequestLine());
            CloseableHttpResponse response = httpClient.execute(httpGet);
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果如下

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值