HttpClient忽略證書錯誤

通常,開發人員將在本地機器上或項目的開發階段使用自簽名證書。 默認情況下,HttpClient(和Web瀏覽器)不會接受不可信的連接。 但是,可以配置HttpClient以允許不可信的自簽名證書。

注意:這是一個可能存在安全風險,因爲您將其用於生產時,基本上會禁用所有的認證檢查,這可通導致受到攻擊。

在這個例子中,我們演示瞭如何忽略Apache HttpClient 4.5中的SSL / TLS證書錯誤。

自簽名證書錯誤

當您嘗試向使用自簽名證書的服務器發出請求並且證書未被客戶端知曉時,將收到以下異常 -

Caused by: 
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: 
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target

Maven依賴關係

我們使用maven來管理依賴關係,並使用Apache HttpClient 4.5版本。 將以下依賴項添加到您的項目中。

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>

接受自簽名證書

我們配置一個自定義的HttpClient。 首先使用SSLContextBuilder設置SSLContext並使用TrustSelfSignedStrategy類來允許自簽名證書。 使用NoopHostnameVerifier本質上關閉主機名驗證。 創建SSLConnectionSocketFactory並傳入SSLContext和HostNameVerifier,並使用工廠方法構建HttpClient。

文件:HttpClientAcceptSelfSignedCertificate.java -

package com.yiibai.httpdemo;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * This example demonstrates how to ignore certificate errors.
 * These errors include self signed certificate errors and hostname verification errors.
 */
public class HttpClientAcceptSelfSignedCertificate {

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

        try (CloseableHttpClient httpclient = createAcceptSelfSignedCertificateClient()) {
            HttpGet httpget = new HttpGet("https://www.yiibai.com");
            System.out.println("Executing request " + httpget.getRequestLine());

            httpclient.execute(httpget);
            System.out.println("----------------------------------------");
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static CloseableHttpClient createAcceptSelfSignedCertificateClient()
            throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        // use the TrustSelfSignedStrategy to allow Self Signed Certificates
        SSLContext sslContext = SSLContextBuilder
                .create()
                .loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();

        // we can optionally disable hostname verification. 
        // if you don't want to further weaken the security, you don't have to include this.
        HostnameVerifier allowAllHosts = new NoopHostnameVerifier();

        // create an SSL Socket Factory to use the SSLContext with the trust self signed certificate strategy
        // and allow all hosts verifier.
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);

        // finally create the HttpClient using HttpClient factory methods and assign the ssl socket factory
        return HttpClients
                .custom()
                .setSSLSocketFactory(connectionFactory)
                .build();
    }
}

執行上面示例代碼,得到以下結果 -

Executing request GET https://www.yiibai.com HTTP/1.1
----------------------------------------