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();
}
}
}
}
运行结果如下