首页 > 代码库 > Android 实现 HttpClient 请求Https
Android 实现 HttpClient 请求Https
如题,默认下,HttpClient是不能请求Https的,需要自己获取
[java] view plaincopy
- private static final int SET_CONNECTION_TIMEOUT = 5 * 1000;
- private static final int SET_SOCKET_TIMEOUT = 20 * 1000;
- public static HttpClient getNewHttpClient() {
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- trustStore.load(null, null);
- SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
- sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
- HttpParams params = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(params, 10000);
- HttpConnectionParams.setSoTimeout(params, 10000);
- HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
- HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
- SchemeRegistry registry = new SchemeRegistry();
- registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
- registry.register(new Scheme("https", sf, 443));
- ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
- HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT);
- HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT);
- HttpClient client = new DefaultHttpClient(ccm, params);
- return client;
- } catch (Exception e) {
- return new DefaultHttpClient();
- }
- }
下面是MySSLSocketFactory类
[java] view plaincopy
- 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();
- }
- }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。