网上有许多对于https的支持配置,但是对于一些新手而言,显然不够直接拿来复制粘贴然后运行出来,所以今天就将整套代码拿出来与大家分享,希望指正错误和帮我优化代码
public static DefaultHttpClient create(boolean isHttps) throws Exception{ HttpParams params = createHttpParams(); DefaultHttpClient httpClient = null; if (isHttps) { // 支持http与https KeyStore trustStore = null; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); schemeRegistry.register(new Scheme("https", sf, 443)); // ThreadSafeClientConnManager线程安全管理类 ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); httpClient = new DefaultHttpClient(cm, params); } catch (Exception e) { } } else { httpClient = new DefaultHttpClient(params); } return httpClient; }
上述代码很明显是获取httpClient的实体,分为支持或者不支持https俩种,简单明了
private static class MySSLSocketFactory extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[]{tm}, null); } @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(); } } private static HttpParams createHttpParams() { final HttpParams params = new BasicHttpParams(); //