HttpGet with HTTPS : SSLPeerUnverifiedException

前端 未结 6 1683
旧时难觅i
旧时难觅i 2020-11-27 13:29

Using HttpClient, I receive the following error when attempting to communicate over HTTPS:

Exception in thread \"main\" javax.net.ssl.SSLPeerUnverifie

6条回答
  •  一个人的身影
    2020-11-27 13:48

    Note: Do not do this in production code, use http instead, or the actual self signed public key as suggested above.

    On HttpClient 4.xx:

    import static org.junit.Assert.assertEquals;
    
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.junit.Test;
    
    public class HttpClientTrustingAllCertsTest {
    
        @Test
        public void shouldAcceptUnsafeCerts() throws Exception {
            DefaultHttpClient httpclient = httpClientTrustingAllSSLCerts();
            HttpGet httpGet = new HttpGet("https://host_with_self_signed_cert");
            HttpResponse response = httpclient.execute( httpGet );
            assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
        }
    
        private DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
            DefaultHttpClient httpclient = new DefaultHttpClient();
    
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, getTrustingManager(), new java.security.SecureRandom());
    
            SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
            Scheme sch = new Scheme("https", 443, socketFactory);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
            return httpclient;
        }
    
        private TrustManager[] getTrustingManager() {
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
    
                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    // Do nothing
                }
    
                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    // Do nothing
                }
    
            } };
            return trustAllCerts;
        }
    }
    

提交回复
热议问题