`

Android Https请求详细demo

 
阅读更多

 

   Android Https详细请求全方案实现,包括HttpUrlConnection及HttpClient方式实现指定证书及信任所有的实现,不多说了,以下代码都经过详细测试,可以直接使用。

    

package com.example.httpstest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

/**
 * HTTPS测试 测试地址:https://certs.cac.washington.edu/CAtest/
 * 测试证书:https://www.washington.edu/itconnect/security/ca/load-der.crt
 * 
 * 
 * @author guojing09
 * 
 */
public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					initSSLWithHttpClinet();
				} catch (Exception e) {
					Log.e("HTTPS TEST", e.getMessage());
				}
			}
		}).start();
	}

	/**
	 * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议
	 * 
	 * @throws CertificateException
	 * @throws IOException
	 * @throws KeyStoreException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public void initSSL() throws CertificateException, IOException, KeyStoreException,
			NoSuchAlgorithmException, KeyManagementException {
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		InputStream in = getAssets().open("load-der.crt");
		Certificate ca = cf.generateCertificate(in);

		KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
		keystore.load(null, null);
		keystore.setCertificateEntry("ca", ca);

		String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
		tmf.init(keystore);

		// Create an SSLContext that uses our TrustManager
		SSLContext context = SSLContext.getInstance("TLS");
		context.init(null, tmf.getTrustManagers(), null);
		URL url = new URL("https://certs.cac.washington.edu/CAtest/");
		HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
		urlConnection.setSSLSocketFactory(context.getSocketFactory());
		InputStream input = urlConnection.getInputStream();

		BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = reader.readLine()) != null) {
			result.append(line);
		}
		Log.e("TTTT", result.toString());
	}

	/**
	 * HttpUrlConnection支持所有Https免验证,不建议使用
	 * 
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */
	public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException {
		URL url = new URL("https://certs.cac.washington.edu/CAtest/");
		SSLContext context = SSLContext.getInstance("TLS");
		context.init(null, new TrustManager[] { new TrustAllManager() }, null);
		HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

			@Override
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}
		});
		HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
		connection.setDoInput(true);
		connection.setDoOutput(false);
		connection.setRequestMethod("GET");
		connection.connect();
		InputStream in = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		String line = "";
		StringBuffer result = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			result.append(line);
		}
		Log.e("TTTT", result.toString());
	}
	
	/**
	 * HttpClient方式实现,支持所有Https免验证方式链接
	 * 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public void initSSLAllWithHttpClient() throws ClientProtocolException, IOException {
		int timeOut = 30 * 1000;
		HttpParams param = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(param, timeOut);
		HttpConnectionParams.setSoTimeout(param, timeOut);
		HttpConnectionParams.setTcpNoDelay(param, true);

		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", TrustAllSSLSocketFactory.getDefault(), 443));
		ClientConnectionManager manager = new ThreadSafeClientConnManager(param, registry);
		DefaultHttpClient client = new DefaultHttpClient(manager, param);

		HttpGet request = new HttpGet("https://certs.cac.washington.edu/CAtest/");
		// HttpGet request = new HttpGet("https://www.alipay.com/");
		HttpResponse response = client.execute(request);
		HttpEntity entity = response.getEntity();
		BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
		StringBuilder result = new StringBuilder();
		String line = "";
		while ((line = reader.readLine()) != null) {
			result.append(line);
		}
		Log.e("HTTPS TEST", result.toString());
	}

	/**
	 * HttpClient方式实现,支持验证指定证书
	 * 
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public void initSSLCertainWithHttpClient() throws ClientProtocolException, IOException {
		int timeOut = 30 * 1000;
		HttpParams param = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(param, timeOut);
		HttpConnectionParams.setSoTimeout(param, timeOut);
		HttpConnectionParams.setTcpNoDelay(param, true);

		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", TrustCertainHostNameFactory.getDefault(this), 443));
		ClientConnectionManager manager = new ThreadSafeClientConnManager(param, registry);
		DefaultHttpClient client = new DefaultHttpClient(manager, param);

		// HttpGet request = new
		// HttpGet("https://certs.cac.washington.edu/CAtest/");
		HttpGet request = new HttpGet("https://www.alipay.com/");
		HttpResponse response = client.execute(request);
		HttpEntity entity = response.getEntity();
		BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
		StringBuilder result = new StringBuilder();
		String line = "";
		while ((line = reader.readLine()) != null) {
			result.append(line);
		}
		Log.e("HTTPS TEST", result.toString());
	}

	public class TrustAllManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
	}

}

 

package com.example.httpstest;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;

import android.os.Build;

public class TrustAllSSLSocketFactory extends SSLSocketFactory {
	private javax.net.ssl.SSLSocketFactory factory;
	private static TrustAllSSLSocketFactory instance;

	private TrustAllSSLSocketFactory() throws KeyManagementException, UnrecoverableKeyException,
			NoSuchAlgorithmException, KeyStoreException {
		super(null);

		SSLContext context = SSLContext.getInstance("TLS");
		context.init(null, new TrustManager[] { new TrustAllManager() }, null);
		factory = context.getSocketFactory();
		setHostnameVerifier(new X509HostnameVerifier() {

			@Override
			public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
				// TODO Auto-generated method stub

			}

			@Override
			public void verify(String host, X509Certificate cert) throws SSLException {
				// TODO Auto-generated method stub

			}

			@Override
			public void verify(String host, SSLSocket ssl) throws IOException {
				// TODO Auto-generated method stub

			}

			@Override
			public boolean verify(String host, SSLSession session) {
				// TODO Auto-generated method stub
				return true;
			}
		});
	}

	public static SocketFactory getDefault() {
		if (instance == null) {
			try {
				instance = new TrustAllSSLSocketFactory();
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnrecoverableKeyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (KeyStoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return instance;
	}

	@Override
	public Socket createSocket() throws IOException {
		return factory.createSocket();
	}

	@Override
	public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
			throws IOException, UnknownHostException {
		if (Build.VERSION.SDK_INT < 11) { // 3.0
			injectHostname(socket, host);
		}

		return factory.createSocket(socket, host, port, autoClose);
	}

	private void injectHostname(Socket socket, String host) {
		try {
			Field field = InetAddress.class.getDeclaredField("hostName");
			field.setAccessible(true);
			field.set(socket.getInetAddress(), host);
		} catch (Exception ignored) {
		}
	}

	public class TrustAllManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
	}

}

 

package com.example.httpstest;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import org.apache.http.conn.ssl.SSLSocketFactory;

import android.content.Context;

public class TrustCertainHostNameFactory extends SSLSocketFactory {

	private static TrustCertainHostNameFactory mInstance;

	public TrustCertainHostNameFactory(KeyStore truststore) throws NoSuchAlgorithmException,
			KeyManagementException, KeyStoreException, UnrecoverableKeyException {
		super(truststore);
	}

	public static TrustCertainHostNameFactory getDefault(Context context) {
		KeyStore keystore = null;
		try {
			CertificateFactory cf = CertificateFactory.getInstance("X.509");
			InputStream in;
			in = context.getAssets().open("load-der.crt");
			Certificate ca = cf.generateCertificate(in);

			keystore = KeyStore.getInstance(KeyStore.getDefaultType());
			keystore.load(null, null);
			keystore.setCertificateEntry("ca", ca);

			if (null == mInstance) {
				mInstance = new TrustCertainHostNameFactory(keystore);
			}
		} catch (Exception e) {

		}
		return mInstance;
	}

	@Override
	public Socket createSocket() throws IOException {
		return super.createSocket();
	}

	@Override
	public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
			throws IOException, UnknownHostException {
		return super.createSocket(socket, host, port, autoClose);
	}

}

 

分享到:
评论
3 楼 求知者long 2016-07-29  
测试证书:https://www.washington.edu/itconnect/security/ca/load-der.crt  这个东西需要去哪里下载呢?

还有 MainActivity 中的initSSLWithHttpClinet()方法是否就是initSSL()方法呢?
2 楼 liuhui880417 2016-03-16  
你这个证书是本地写死到assert路径下的,安全吗?我觉得本地的证书是不是应该从服务器端下发下来? 如果不是服务器端下发下来的,一个是别人也可以盗用你assert路径下的那个文件,另一个是如果证书后期变动了的话,那用这个证书的用户,还能得到服务器端的验证通过吗?
1 楼 BigBird2012 2015-07-06  
initSSLWithHttpClinet 这个方法在哪里?

相关推荐

    Android网络请求OkHttp的使用demo代码

    本篇将详细讲解如何在Android中使用OkHttp进行网络请求,并提供一个简单的Demo代码。 首先,理解OkHttp的核心优势:它提供了缓存机制,减少了不必要的网络请求;支持HTTP/2和SPDY协议,能有效减少网络延迟;并且...

    Android 网络请求的那些事Demo

    综上所述,“Android 网络请求的那些事Demo”涵盖了Android网络请求的基本概念、常用方法以及一些最佳实践,对于理解和实现Android应用的网络功能具有很好的指导意义。开发者应根据项目需求选择合适的HTTP库,并注意...

    Android异步请求网络图片demo

    "Android异步请求网络图片demo"是一个示例项目,旨在演示如何在Android应用中有效地、非阻塞地下载并显示网络上的图片。这个项目的核心知识点主要包括以下几个方面: 1. **AsyncTask**: Android提供了`AsyncTask`类...

    Android 网络请求代码和demo.apk

    ## 一、主要内容 1、开发网络请求前的基本准备 2、普通网络请求代码 3、使用OkHttp网络框架请求网络代码 4、使用Retrofit网络框架请求网络代码 5、使用WebView显示对应网址的网页 6、应用demo的相关代码和apk

    Android开发 okhttp网络请求使用demo,包括上传文件方法封装

    本示例"Android开发 okhttp网络请求使用demo,包括上传文件方法封装"将帮助开发者理解如何利用OkHttp进行网络请求,特别是文件上传的功能。 首先,我们来了解OkHttp的基本概念。OkHttp是由Square公司开发的一款HTTP...

    android https demo

    以上就是关于“android https demo”的详细知识,通过这个Demo,开发者可以学习如何在Android应用中安全地使用HTTPS进行网络通信,确保用户的隐私和数据安全。实践中,一定要注意遵循最佳安全实践,以防范潜在的安全...

    Android Async-Http Demo

    "Android Async-Http Demo"是一个基于Android平台的示例项目,展示了如何使用Async-Http库来实现高效、非阻塞的HTTP网络请求。这个Demo旨在帮助开发者理解并实践异步HTTP通信的基本原理和最佳实践。 Async-Http库,...

    curl在Android中使用的Demo

    在Android开发中,`curl`常被用来调试网络请求,理解API接口的工作方式,或者快速验证网络服务的响应。这篇博客文章《curl在Android中使用的Demo》将向我们展示如何在Android应用中集成和使用`curl`命令。 首先,...

    Android在线视频播放器Demo

    总的来说,"Android在线视频播放器Demo"是一个展示如何在Android应用中实现实时播放网络视频的实例。通过学习和理解这个Demo,开发者可以掌握Vitamio库的使用,以及如何处理网络视频播放的各种细节,从而提升应用的...

    Android使用Https访问Demo

    本文将深入探讨如何在Android应用中实现HTTPS协议的访问,基于提供的"Android使用Https访问Demo",我们将详细解析这一过程。 首先,HTTPS(HyperText Transfer Protocol Secure)是一种基于SSL/TLS的安全通信协议,...

    android 蓝牙数据传输DEMO

    下面将详细讲解这个DEMO涉及的关键知识点。 1. **蓝牙API**:Android提供了`BluetoothAdapter`、`BluetoothDevice`、`BluetoothServerSocket`和`BluetoothSocket`等类来处理蓝牙连接和通信。这些类位于`android....

    android调用拍照存储demo

    下面将详细解释这个Demo中的关键知识点。 首先,我们需要在AndroidManifest.xml文件中添加必要的权限。因为涉及到读写SD卡以及访问相机,所以需要`READ_EXTERNAL_STORAGE`和`WRITE_EXTERNAL_STORAGE`权限: ```xml...

    安卓 http 各种方式请求DEMO

    - 提到的DEMO_JAVA可能包含了服务端的Java代码,这部分代码用于处理来自Android客户端的Socket请求,可能包含接收数据、解析数据、执行业务逻辑和返回响应等操作。 6. **使用注意事项**: - 网络请求应在主线程...

    Android官方提供的SipDemo

    【Android SipDemo详解】 Android SipDemo是一个官方提供的示例应用,用于演示如何在Android平台上使用SIP(Session Initiation Protocol)进行VoIP(Voice over IP)通信。这个项目对于开发者来说,尤其是那些想要...

    Android Wifi开发Demo示例

    总结,这个Android Wi-Fi开发Demo示例提供了一个完整的流程,从查找可用的Wi-Fi网络,到连接选定的网络,再到通过Wi-Fi进行数据交换,为开发者提供了实践和学习Android Wi-Fi编程的基础。理解并掌握这些知识点,有助...

    Android通讯录详细demo

    本教程将深入探讨如何在Android应用中实现对通讯录的获取、添加、删除等操作,通过提供的"Android通讯录详细demo",你可以更好地理解这些概念。 首先,让我们了解Android系统中的通讯录API。Android提供了一个名为`...

    Android一些应用demo

    综上所述,`AndroidDemo`这个项目可能包含了使用Volley进行网络请求、PickView实现选择器交互以及GIS地图功能的示例代码。通过学习和研究这些示例,开发者可以加深对这些技术的理解,并将它们应用到自己的项目中,...

    Android官方Wifi P2P Demo

    **Android官方Wifi P2P Demo详解** Android的Wi-Fi Direct(也称为Wi-Fi Peer-to-Peer或P2P)是一项技术,允许设备之间直接建立高速、低延迟的无线连接,无需通过传统的Wi-Fi接入点。这项功能使得Android设备能够...

    Android二维码扫描Demo 程序源码

    这份"Android二维码扫描Demo程序源码"是一个很好的学习资源,它涵盖了如何在Android应用中集成二维码扫描的基本步骤和关键技术点。下面我们将深入探讨这个话题。 首先,Android二维码扫描通常依赖于第三方库,如...

    Android 网络请求

    在DEMO中,`NetworkTest`可能包含了实现上述步骤的代码,你可以通过学习和调试这个DEMO来深入理解Android中的网络请求。记住,为了适应不同的网络环境和服务器响应,你应该对错误进行适当的处理,如重试机制、状态码...

Global site tag (gtag.js) - Google Analytics