JDK 获取 https 的服务器证书文件

Nov 21, 2023

JDK 获取 https 的服务器证书文件。


import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.testng.annotations.Test;

@Test
public class ChunkBodyProcessorTest {

  // java 11+
  @Test
  public void multipleChunk0() throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpResponse<Void> res = client.send(
        HttpRequest.newBuilder().GET().uri(URI.create("https://www.baidu.com/")).build(),
        HttpResponse.BodyHandlers.discarding());
    SSLSession ssl = res.sslSession().get();
    Certificate[] cert = ssl.getPeerCertificates();
    for (int i = 0; i < cert.length; i++) {
      if (cert[i] instanceof X509Certificate x) {
        System.out.println(x.getSubjectX500Principal().getName());
        System.out.println("\t\t" + x.getNotBefore() + " - " + x.getNotAfter());
        // xx.cer 文件, 也可以换成 64 字符一行, 开头:-----BEGIN CERTIFICATE-----\n , 结尾:-----END CERTIFICATE-----
        // System.out.println(Base64.encode(ax.getEncoded()));
      }
    }
  }

  // java 1.8+
  @Test
  public void multipleChunks() throws Exception {
    URL url = new URL("https://www.baidu.com/");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(1000);
    conn.connect();
    Certificate[] cer = conn.getServerCertificates();
    for (Certificate c : cer) {
      if (c instanceof X509Certificate ax) {
        System.out.println(ax.getSubjectX500Principal().getName());
        System.out.println("\t\t" + ax.getNotBefore() + "-" + ax.getNotAfter());
        // xx.cer 文件, 也可以换成 64 字符一行
        // System.out.println(Base64.encode(ax.getEncoded()));
      } else {
        System.out.println("Not support !!!" + c.getClass().getName());
      }
    }
  }
}

<完>