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

你可能感兴趣的:(android)