HttpClient ssl 无验证
in java on httpclient - Hits()
今天发现httpclient完全是个版本帝,前段时间刚刚从升级到4.o,丢弃曾经熟悉的使用结构。这次升级到4.2后里面又一堆方法被丢弃了。
看着写的类一堆黄行行,心里确实不舒服,这里干个时髦。
Httpclient创建ssl无验证的工厂代码:
public static HttpClient getHttpClient() { if (httpClient != null) return httpClient; BasicHttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 45000); HttpConnectionParams.setSoTimeout(params, 30000); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); try { // NOTE: here we trust all ssl certification SSLContext sslContext = SSLContext.getInstance("TLS"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new TrustAllX509TrustManager() { } }, null); SSLSocketFactory sf = new TrustAllSSLSocketFactory(sslContext); registry.register(new Scheme("https", 443, sf)); } catch (Exception e) { Log.warn("Unable to register HTTPS socket factory: " + e.getLocalizedMessage()); } PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(registry); httpClient = new DefaultHttpClient(connManager, params); return httpClient; }
public class TrustAllSSLSocketFactory extends SSLSocketFactory { SSLContext sslContext; public TrustAllSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); if (null == sslContext) { sslContext = SSLContext.getInstance("TLS"); } TrustManager tm = new TrustAllX509TrustManager() { }; sslContext.init(null, new TrustManager[] { tm }, null); } public TrustAllSSLSocketFactory(SSLContext sslContext2) { super(sslContext2, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sslContext = sslContext2; } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } }
public class TrustAllX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }
不知道多长时间又会更新。