how to make Unirest(java) ignore certificate error

后端 未结 5 1801
无人及你
无人及你 2021-02-04 07:42

I am using Unirest (java version) to make GET and POST request.But I encounter a problem when accessing SSL encrypted site , since my program is behind a corporate network and t

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 08:20

    Unfortunately, Unirest does not have a native way to configure SSL, so providing a custom HttpClient instance looks like the only option. Here is a solution, which does not use deprecated classes (like 'DefaultHttpClient') and works with self-signed certificates:

    protected void prepareHttpsClient() {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        try {
            String certificateStorage = <>;
            String certificatePassword = <>;
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(
                new File(certificateStorage), certificatePassword.toCharArray(),
                new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1"}, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            clientBuilder.setSSLSocketFactory(sslFactory);
        }
        catch (Exception e) {
            throw new IllegalArgumentException("Error configuring server certificates.", e);
        }
        HttpClient httpClient = clientBuilder.build();
        Unirest.setHttpClient(httpClient);
    }
    

提交回复
热议问题