HttpClient獲取伺服器證書


以下教學演示了如何使用Apache HttpClient 4.5從資源伺服器獲取證書。 證書用於通過使用SSL / TLS的HTTPS保護用戶端和伺服器之間的連線。 當您需要有關證書的詳細資訊時,例如:證書何時到期?誰頒發證書?等等。或者在某些情況下需要讀取伺服器證書。 在下面的例子中,我們將詳細解釋如何實現。

Maven依賴關係

我們使用maven來管理依賴關係,並使用Apache HttpClient 4.5版本。 將以下依賴項新增到您的專案中,以便建立HTTP DELETE請求方法。

pom.xml 檔案的內容如下 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

HTTP獲取伺服器證書範例

在以下範例中,我們向https://www.baidu.com發出請求以獲取伺服器證書。 首先,我們建立一個HttpResponseInterceptor,它將從SSLSession中讀取證書(如果存在),並將證書新增到HttpContext中,以便稍後用於處理。

接下來,建立一個自定義的HttpClient並使用addInterceptorLast()工廠方法新增攔截器。

最後,向資源伺服器發出一個HttpGet請求,並從HttpContext獲取伺服器證書,我們之前將它們放在這裡。 現在擁有了證書,然後遍歷集合併將一些資料列印到控制台。

檔案:HttpClientGetServerCertificate.java -

package com.yiibai.httpdemo;

import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

/**
 * This example demonstrates how to obtain server certificates {@link X509Certificate}.
 */
public class HttpClientGetServerCertificate {

    public static final String PEER_CERTIFICATES = "PEER_CERTIFICATES";

    public static void main(String... args) throws IOException {

        // create http response certificate interceptor
        HttpResponseInterceptor certificateInterceptor = (httpResponse, context) -> {
            ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection)context.getAttribute(HttpCoreContext.HTTP_CONNECTION);
            SSLSession sslSession = routedConnection.getSSLSession();
            if (sslSession != null) {

                // get the server certificates from the {@Link SSLSession}
                Certificate[] certificates = sslSession.getPeerCertificates();

                // add the certificates to the context, where we can later grab it from
                context.setAttribute(PEER_CERTIFICATES, certificates);
            }
        };

        // create closable http client and assign the certificate interceptor
        CloseableHttpClient httpClient = HttpClients.custom().addInterceptorLast(certificateInterceptor).build();

        try {

            // make HTTP GET request to resource server
            HttpGet httpget = new HttpGet("https://www.baidu.com");
            System.out.println("Executing request " + httpget.getRequestLine());

            // create http context where the certificate will be added
            HttpContext context = new BasicHttpContext();
            httpClient.execute(httpget, context);

            // obtain the server certificates from the context
            Certificate[] peerCertificates = (Certificate[])context.getAttribute(PEER_CERTIFICATES);

            // loop over certificates and print meta-data
            for (Certificate certificate : peerCertificates){
                X509Certificate real = (X509Certificate) certificate;
                System.out.println("----------------------------------------");
                System.out.println("Type: " + real.getType());
                System.out.println("Signing Algorithm: " + real.getSigAlgName());
                System.out.println("IssuerDN Principal: " + real.getIssuerX500Principal());
                System.out.println("SubjectDN Principal: " + real.getSubjectX500Principal());
                System.out.println("Not After: " + DateUtils.formatDate(real.getNotAfter(), "dd-MM-yyyy"));
                System.out.println("Not Before: " + DateUtils.formatDate(real.getNotBefore(), "dd-MM-yyyy"));
            }

        } finally {
            // close httpclient
            httpClient.close();
        }
    }
}

執行上面範例程式碼,得到以下結果 -

Executing request GET https://www.baidu.com HTTP/1.1
----------------------------------------
Type: X.509
Signing Algorithm: SHA256withRSA
IssuerDN Principal: CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US
SubjectDN Principal: CN=baidu.com, OU=service operation department., O="BeiJing Baidu Netcom Science Technology Co., Ltd", L=beijing, ST=beijing, C=CN
Not After: 17-08-2018
Not Before: 29-06-2017
----------------------------------------
Type: X.509
Signing Algorithm: SHA256withRSA
IssuerDN Principal: CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
SubjectDN Principal: CN=Symantec Class 3 Secure Server CA - G4, OU=Symantec Trust Network, O=Symantec Corporation, C=US
Not After: 30-10-2023
Not Before: 31-10-2013
----------------------------------------
Type: X.509
Signing Algorithm: SHA1withRSA
IssuerDN Principal: OU=Class 3 Public Primary Certification Authority, O="VeriSign, Inc.", C=US
SubjectDN Principal: CN=VeriSign Class 3 Public Primary Certification Authority - G5, OU="(c) 2006 VeriSign, Inc. - For authorized use only", OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
Not After: 07-11-2021
Not Before: 08-11-2006