`
月下独酌
  • 浏览: 127854 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

android https之二

 
阅读更多
android https之一
android https之二
android https之三
	private HttpClient makeHttpsClient(String keyStorePasswd, int port) {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());
			String trustStorePath = System
					.getProperty("javax.net.ssl.trustStore");
			// File keystoreFile = new File(trustStorePath);
			// 由于android权限原因,无法读取trustStorePath="//system/etc/security/cacerts.bks"文件,此处由sdcard代替
			File keystoreFile = new File("/sdcard/cacerts.bks");
			trustStore.load(new FileInputStream(keystoreFile), keyStorePasswd
					.toCharArray());
			SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
			socketFactory.setHostnameVerifier(new X509HostnameVerifier() {
				public boolean verify(String host, SSLSession session) {
					return true;
				}

				public void verify(String host, SSLSocket ssl)
						throws IOException {
				}

				public void verify(String host, X509Certificate cert)
						throws SSLException {
				}

				public void verify(String host, String[] cns,
						String[] subjectAlts) throws SSLException {
				}
			});
			Scheme sch = new Scheme("https", socketFactory, port);
			HttpClient httpClient = new DefaultHttpClient();
			httpClient.getConnectionManager().getSchemeRegistry().register(sch);
			return httpClient;
		} catch (KeyStoreException e) {
			Log.e("xx", e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			Log.e("xx", e.getMessage());
		} catch (CertificateException e) {
			Log.e("xx", e.getMessage());
		} catch (KeyManagementException e) {
			Log.e("xx", e.getMessage());
		} catch (UnrecoverableKeyException e) {
			Log.e("xx", e.getMessage());
		} catch (IOException e) {
			Log.e("xx", e.getMessage());
		}
		return null;
	}

	private void sendrequest() {
		try {
			HttpClient httpClient = makeHttpsClient("changeit", 8443);
			HttpPost httpPost = makeHttpPost("https://10.167.17.187:8443");
			HttpResponse response;
			response = httpClient.execute(httpPost);

			if (response != null) {
				Log.i("xx", "" + response.getStatusLine().getStatusCode());
			} else {
				Log.i("xx", "NULL");
			}
		} catch (ClientProtocolException e) {
			Log.e("xx", e.getMessage());
		} catch (IOException e) {
			Log.e("xx", e.getMessage());
		}
	}

分享到:
评论
2 楼 月下独酌 2012-09-26  
sxchao2008 写道
/sdcard/cacerts.bks 这个证书可以到网上随便下一个吗? 如果不行 该如何生成? 我需要客户端通过https连接server端 。是否在server端也需要这么一个证书?

bks是android系统使用的证书库文件格式,是用来存储密钥key的。

在服务器端配置https的时候可以使用其他格式的证书库,比如jks格式的,这个和客户端没关系。

android系统中有一个自带的bks文件,root以后可以直接拿出来,在//system/etc/security/cacerts.bk这个目录下,默认密码是changeit,当然在网上随意下载一个也可以,但是要知道证书库的密码。

如果要自己制作bks证书库文件的话,请参考http://blog.csdn.net/hezhipin610039/article/details/7074000
1 楼 sxchao2008 2012-09-26  
/sdcard/cacerts.bks 这个证书可以到网上随便下一个吗? 如果不行 该如何生成? 我需要客户端通过https连接server端 。是否在server端也需要这么一个证书?

相关推荐

Global site tag (gtag.js) - Google Analytics