Android Https请求详细demo

标签: android https demo | 发表时间:2014-11-06 18:26 | 作者:gjican
出处:http://www.iteye.com

 

   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);
	}

}

 



已有 0 人发表留言,猛击->> 这里<<-参与讨论


ITeye推荐



相关 [android https demo] 推荐:

Android Https请求详细demo

- - 移动开发 - ITeye博客
   Android Https详细请求全方案实现,包括HttpUrlConnection及HttpClient方式实现指定证书及信任所有的实现,不多说了,以下代码都经过详细测试,可以直接使用. * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议.

Android dlib人脸识别 dlib-android-app: Android app to demo dlib-android(https://github.com/tzutalin/dlib-android). Use the prebuilt shared-lib built from dlib-android

- -

android的Notifications的例子demo

- - 博客园_首页
android的Notifications通知的原理和Demo.   在APP中经常会用到通知. 比如网易新闻客户端,有什么重大新闻的话会在通知栏弹出一条通知.   在做程序过程中我也遇到这个需求. 每隔7天就自动弹出通知,提醒用户. 在网上搜了搜,用了2天时间实现了.   一:通知要调用闹钟功能来实现,第一步设置闹钟.

Android Https相关完全解析 当OkHttp遇到Https

- - CSDN博客推荐文章
本文出自: 【张鸿洋的博客】. 其实这篇文章理论上不限于okhttp去访问自签名的网站,不过接上篇博文了,就叫这个了. 首先要了解的事,okhttp默认情况下是支持https协议的网站的,比如 https://www.baidu.com, https://github.com/hongyangAndroid/okhttp-utils等,你可以直接通过okhttp请求试试.

百度地图SDK for Android【Demo Place详情页】

- - CSDN博客移动开发推荐文章
        Place详情展示页面可以帮助开发者便捷的展示Poi详情信息,此外通过详情展示页面您还可以实现电话的拨打等功能. 今天将向大家介绍Place详情页的具体使用方法.         第一步,创建工程,并放置基础地图mapview控件(详细介绍请参考: 百度地图SDK for Android【Demo地图展示】 ).

android gps开发必备资料(含测试demo下载)

- - CSDN博客推荐文章
int year = ca.get(Calendar.YEAR);//获取年份. int month=ca.get(Calendar.MONTH);//获取月份. int day=ca.get(Calendar.DATE);//获取日. int minute=ca.get(Calendar.MINUTE);//分.

Activiti工作流demo

- - CSDN博客综合推荐文章
继上篇《 Activiti工作流的环境配置》.        前几篇对Activiti工作流进行了介绍,并讲解了其环境配置. 本篇将会用一个demo来展示Activiti工作流具体的体现,直接上干货.        以HelloWorld程序为例.       首先说一下业务流程,员工张三提交了一个申请,然后由部门经理李四审核,审核通过后再由总经理王五审核,通过则张三申请成功.

https协议

- - 互联网 - ITeye博客
SSL 协议的握手过程   .       为了便于更好的认识和理解 SSL 协议,这里着重介绍 SSL 协议的握手协议. SSL 协议既用到了公钥加密技术(非对称加密)又用到了对称加密技术,SSL对传输内容的加密是采用的对称加密,然后对对称加密的密钥使用公钥进行非对称加密. 这样做的好处是,对称加密技术比公钥加密技术的速度快,可用来加密较大的传输内容,公钥加密技术相对较慢,提供了更好的身份认证技术,可用来加密对称加密过程使用的密钥.

Go和HTTPS

- - Tony Bai
近期在构思一个产品,考虑到安全性的原因,可能需要使用到 HTTPS协议以及双向数字证书校验. 之前只是粗浅接触过HTTP( 使用Golang开 发微信系列). 对HTTPS的了解则始于那次 自行搭建ngrok服务,在那个过程中照猫画虎地为服务端生成了一些私钥和证书,虽然结果是好 的:ngrok服务成功搭建起来了,但对HTTPS、数字证书等的基本原理并未求甚解.

Y Combinator 举办 Demo Day

- Radar - 丕子
世界上最大的创业公司孵化器 Y Combinator 今天举办他们的 Demo Day,这次一共有 63 家创业公司参加演示,其中有 31 家愿意向媒体和投资人曝光自己,下面是这些创业公司的名字以及一句话描述:. Aisle50: 杂货版 Groupon. Interstate: 项目管理软件,可以跟客户分享开发路线图.