Liping Huang Liping Huang - 1 year ago 156
Java Question

HttpClient peer not authenticated when time shifted?

Due to the requirement, we need test the https connection by shift the system date to a future date like 2025-05-05, the problem is when using the

(version 4.2), will encounter the exception peer not authenticated

The simple code segment as below:

public void httpsShouldWorking() throws Exception {

HttpClient client = new DefaultHttpClient();

String urlOverHttps = "https://URL";
HttpGet getMethod = new HttpGet(urlOverHttps);
HttpResponse response = client.execute(getMethod);

assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

Also I google it and found a solution HttpClient with SSL

as mentioned:

Let’s now configure the http client to trust all certificate chains regardless of their validity:

But after the try, it is not working and still get the auth exception.

Is there a solution to avoid the auth when shift the system date?

Answer Source

It is possible to make HttpClient get around the checks of SSL certificate validity. This code can be used to obtain an instance of HttpClient:

private static HttpClient getHttpClient() {

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

                new TrustManager[]{new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {

                        return null;

                    public void checkClientTrusted(
                            X509Certificate[] certs, String authType) {


                    public void checkServerTrusted(
                            X509Certificate[] certs, String authType) {

                }}, new SecureRandom());

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();

        return httpClient;

    } catch (Exception e) {
        return HttpClientBuilder.create().build();

The exception will no longer be thrown, when the certification is expired, the browser will issues a warning about an expired certificate and let user confirm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download