前言:
在android開發中,會涉及到安全比較高的業務,比如銀行,網上交易等,這就涉及到https協議的互動
對於https 互動過程分兩個階段
1. 用戶端擷取伺服器的認證,並驗證認證的內容是否可信
2. 用戶端和伺服器端進行握手協議,並進行資料轉送
對於https 互動過程,第一點,採用了網站可信的方式,如有需要驗證網域名稱和認證是否一致的,請自我擴充
實現的過程:
1): 註冊scheme of https
注意:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
如果需要驗證,則,自己繼承HostnameVerifier ,並實現介面。
2):擷取 httpClient 和 httpPost
3):擷取資料
下面是實現的源碼,參數就是https路徑:
1 public String GetData(String URL)
2 {
3 String returns="";
4
5 //Step One register scheme of https
6 HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
7
8 SchemeRegistry registry = new SchemeRegistry();
9 SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
10 socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
11 registry.register(new Scheme("https", socketFactory, 443));
12 registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory (), 80));
13
14 //Step Two Get httpClient and httpPost
15
16 DefaultHttpClient client = new DefaultHttpClient();
17 SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
18 DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
19 //------- Set verifier
20 HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
21 // -------Example send http request
22 // final String url = "https://martinreichart.com/_tmpdata/login_valid.json";
23 HttpPost httpPost = new HttpPost(URL);
24
25 //Step Three Get Data
26 try {
27 HttpResponse response = httpClient.execute(httpPost);
28 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
29 // 解析返回的內容
30 returns = EntityUtils.toString(response.getEntity());
31 }
32 }
33 catch(Exception ex)
34 {
35
36 String aa =ex.toString();
37 }
38
39 return returns;
40 }
特別感謝:卓易點評網 ( 發布Android 應用新去處)贊助支援!!!