Android应用中访问HTTPS方式

本文介绍了HTTPS的基本概念,强调其安全特性,并对比了HTTPS与HTTP的区别。文章详细讲解了在Android应用中如何使用自定义证书进行HTTPS连接,包括证书导入和使用BouncyCastleProvider的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



       HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版。即HTTP下加入SSL层,HTTPS的安全基础是SSL,因此加密的详细内容就需要SSL。 它是一个URI scheme(抽象标识符体系),句法类同http:体系。用于安全的HTTP数据传输。https:URL表明它使用了HTTP,但HTTPS存在不同于HTTP的默认端口及一个加密/身份验证层(在HTTP与TCP之间)。这个系统的最初研发由网景公司(Netscape)进行,并内置于其浏览器Netscape Navigator中,提供了身份验证与加密通讯方法。现在它被广泛用于万维网上安全敏感的通讯,例如交易支付方面。

HTTPS和HTTP的区别

一、https协议需要到ca申请证书,一般免费证书很少,需要交费。

二、http是超文本传输协议,信息是明文传输,https 则是具有安全性的ssl加密传输协议。

三、http和https使用的是完全不同的连接方式,用的端口也不一样,前者是80,后者是443。

四、http的连接很简单,是无状态的;HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,比http协议安全。

第一种使用自定义证书 

SSLSocketFactory.getSocketFactory() 使用自定义证书不被系统承认

	/**
	 * 使用自定义证书并忽略验证的HTTPS连接方式
	 */
	public static void GetNetWork() {
		try {
			String path = "https://192.168.0.102:8443/123.html";

			BasicHttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params,
					HTTP.DEFAULT_CONTENT_CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);

			SSLSocketFactory.getSocketFactory().setHostnameVerifier(
					new AllowAllHostnameVerifier());

			SchemeRegistry schReg = new SchemeRegistry();

			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			// 出错:因为使用了不被系统承认的自定义证书:No peer certificate 。

			// schReg.register(new Scheme("https",SSLSocketFactory.getSocketFactory(), 443));

			schReg.register(new Scheme("https", SSLTrustAllSocketFactory
					.getSocketFactory(), 443));
			ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
					params, schReg);
			DefaultHttpClient client = new DefaultHttpClient(connMgr, params);

			HttpGet request = new HttpGet(path);

			HttpResponse httpResponse = client.execute(request);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			String message = httpResponse.getStatusLine().getReasonPhrase();
			HttpEntity entity = httpResponse.getEntity();
			if (responseCode == 200 && entity != null) {
				Log.e("log", entity.toString());
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static class SSLTrustAllSocketFactory extends SSLSocketFactory {

		private static final String TAG = "SSLTrustAllSocketFactory";
		private SSLContext mCtx;

		public class SSLTrustAllManager implements X509TrustManager {

			@Override
			public void checkClientTrusted(X509Certificate[] arg0, String arg1)
					throws CertificateException {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] arg0, String arg1)
					throws CertificateException {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}

		}

		public SSLTrustAllSocketFactory(KeyStore truststore) throws Throwable {
			super(truststore);
			try {
				mCtx = SSLContext.getInstance("TLS");
				mCtx.init(null,
						new TrustManager[] { new SSLTrustAllManager() }, null);

				setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			} catch (Exception ex) {
			}
		}

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

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

		public static SSLSocketFactory getSocketFactory() {
			try {
				KeyStore trustStore = KeyStore.getInstance(KeyStore
						.getDefaultType());
				trustStore.load(null, null);
				SSLSocketFactory factory = new SSLTrustAllSocketFactory(
						trustStore);
				return factory;
			} catch (Throwable e) {
				Log.d(TAG, e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

	}
第二种  直接从 https://kyfw.12306.cn/otn/ 下载根证书 导入应用中 验证 

public static void GetNetWork2(Context context) {
		try {
			String path = "https://kyfw.12306.cn/otn/";

			BasicHttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params,
					HTTP.DEFAULT_CONTENT_CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);

			SSLSocketFactory.getSocketFactory().setHostnameVerifier(
					new AllowAllHostnameVerifier());

			SchemeRegistry schReg = new SchemeRegistry();

			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLCustomSocketFactory
					.getSocketFactory(context), 443));
			ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
					params, schReg);
			DefaultHttpClient client = new DefaultHttpClient(connMgr, params);

			HttpGet request = new HttpGet(path);

			HttpResponse httpResponse = client.execute(request);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			String message = httpResponse.getStatusLine().getReasonPhrase();
			HttpEntity entity = httpResponse.getEntity();
			if (responseCode == 200 && entity != null) {
				Log.e("log", entity.toString());
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static class SSLCustomSocketFactory extends SSLSocketFactory {
		private static final String TAG = "SSLCustomSocketFactory";

		private static final String KEY_PASS = "123456";

		public SSLCustomSocketFactory(KeyStore trustStore) throws Throwable {
			super(trustStore);
		}

		public static SSLCustomSocketFactory getSocketFactory(Context context) {
			InputStream ins = null;
			KeyStore trustStore;
			try {
				ins = context.getResources().openRawResource(R.raw.srca);

				trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

				trustStore.load(null);
				CertificateFactory certificateFactory = CertificateFactory
						.getInstance("X.509");
				String certificateAlias = Integer.toString(2);
				trustStore.setCertificateEntry(certificateAlias,
						certificateFactory.generateCertificate(ins));
				ins.close();

				SSLCustomSocketFactory factory = new SSLCustomSocketFactory(
						trustStore);
				return factory;
			} catch (KeyStoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (CertificateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(ins!=null){
					try {
						ins.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
			return null;
		}
	}

不论是浏览器导出,还是服务器端获得,都是公钥证书,有两种格式:纯文本的.crt格式或是二进制的.cer格式。两种都可以用。

然后,你如果需要一个特定版本的JCE Provider,然后在这个目录下运行以下命令: keytool -importcert -v -trustcacerts -alias cert12306 -file srca.cer -keystore cert12306.bks -storetype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk15on-148.jarr -storepass 123456 

生成cert12306.bks文件 导入应用中

public static void GetNetWork3(Context context) {
		try {
			String path = "https://kyfw.12306.cn/otn/";

			BasicHttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params,
					HTTP.DEFAULT_CONTENT_CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);

			SSLSocketFactory.getSocketFactory().setHostnameVerifier(
					new AllowAllHostnameVerifier());

			SchemeRegistry schReg = new SchemeRegistry();

			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLCustomSocketFactory2
					.getSocketFactory(context), 443));
			ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
					params, schReg);
			DefaultHttpClient client = new DefaultHttpClient(connMgr, params);

			HttpGet request = new HttpGet(path);

			HttpResponse httpResponse = client.execute(request);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			String message = httpResponse.getStatusLine().getReasonPhrase();
			HttpEntity entity = httpResponse.getEntity();
			if (responseCode == 200 && entity != null) {
				Log.e("log", entity.toString());
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static class SSLCustomSocketFactory2 extends SSLSocketFactory {
		private static final String TAG = "SSLCustomSocketFactory";

		private static final String KEY_PASS = "123456";

		public SSLCustomSocketFactory2(KeyStore trustStore) throws Throwable {
			super(trustStore);
		}

		public static SSLCustomSocketFactory2 getSocketFactory(Context context) {
			InputStream ins = null;
			KeyStore trustStore;
			try {
				ins = context.getResources().openRawResource(R.raw.cert12306);

				trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

				trustStore.load(ins, KEY_PASS.toCharArray());

		SSLCustomSocketFactory2 factory = new SSLCustomSocketFactory2(
						trustStore);
				return factory;
			} catch (KeyStoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (CertificateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(ins!=null){
					try {
						ins.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
			return null;
		}
	}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值