Accept server's self-signed ssl certificate in Java client

后端 未结 12 1514
日久生厌
日久生厌 2020-11-22 00:04

It looks like a standard question, but I couldn\'t find clear directions anywhere.

I have java code trying to connect to a server with probably self-signed (or expir

12条回答
  •  無奈伤痛
    2020-11-22 00:34

    Apache HttpClient 4.5 supports accepting self-signed certificates:

    SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial(new TrustSelfSignedStrategy())
        .build();
    SSLConnectionSocketFactory socketFactory =
        new SSLConnectionSocketFactory(sslContext);
    Registry reg =
        RegistryBuilder.create()
        .register("https", socketFactory)
        .build();
    HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);        
    CloseableHttpClient httpClient = HttpClients.custom()
        .setConnectionManager(cm)
        .build();
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse sslResponse = httpClient.execute(httpGet);
    

    This builds an SSL socket factory which will use the TrustSelfSignedStrategy, registers it with a custom connection manager then does an HTTP GET using that connection manager.

    I agree with those who chant "don't do this in production", however there are use-cases for accepting self-signed certificates outside production; we use them in automated integration tests, so that we're using SSL (like in production) even when not running on the production hardware.

提交回复
热议问题