之前的HttpClient一直都是寫成
HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); try{ TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { //To change body of implemented methods use File | Settings | File Templates. } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { //To change body of implemented methods use File | Settings | File Templates. } public java.security.cert.X509Certificate[] getAcceptedIssuers() { // return new java.security.cert.X509Certificate[0]; //To change body of implemented methods use File | Settings | File Templates. return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{easyTrustManager}, null); SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); httpclient.getConnectionManager().getSchemeRegistry().register( new Scheme("https", 443, socketFactory) ); httpclient.getConnectionManager().getSchemeRegistry().register( new Scheme("http", 80, PlainSocketFactory.getSocketFactory()) ); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); }
自從Apache的HttpComponents Client4.3模組,許多函式庫都已經deprecated了。
今天趁著心情好,將整個改了一下:
try{ TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { //To change body of implemented methods use File | Settings | File Templates. } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { //To change body of implemented methods use File | Settings | File Templates. } public java.security.cert.X509Certificate[] getAcceptedIssuers() { // return new java.security.cert.X509Certificate[0]; //To change body of implemented methods use File | Settings | File Templates. return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{easyTrustManager}, null); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); this.httpclient = HttpClients.custom().setSSLSocketFactory( sslsf ).build(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); }
廣告