首页 > 解决方案 > Spring Boot 2.5、Java 15 - Java HttpClient 或 Apache HttpClient,检查目标证书的 CN

问题描述

是否可以提交一个String值来检查(如果它等于)目标证书的CN(值)?String

我用

HttpRequest request = HttpRequest.newBuilder()
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .uri(URI.create("https://<ip-address>/..."))
    .timeout(Duration.ofMillis(1000))
    .build();

HttpResponse<String> response;
try {
    response = HttpClient.newBuilder()
        .version(Version.HTTP_1_1)
        .authenticator(this.authenticator)
        .build()
        .send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException iex) {
} catch (IOException ioex) {
}

或者,如果无法提交,也许可以定义或设置一个方法,该方法从目标证书中读取 CN,并根据另一个 String 值检查该值。

一种解决方案HttpsURLConnection是:

    HostnameVerifier myHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            // check what ever, example CN from certificat
            Certificate[] peerCertificates = session.getPeerCertificates();
            Certificate peerCertificate = peerCertificates[0];
            ...
            return <true> or <false>;
        }
    }
    
    HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); 
    con.setHostnameVerifier(myHostnameVerifier);

工作HttpsURLConnection意味着使用OutputStreamand InputStream,这是老式的风格。

这也可以用 JavaHttpClient或 Apache HttpClient 完成吗?我必须并行运行许多这些连接。

标签: javaspring-bootapache-httpclient-4.x

解决方案


推荐阅读