(android 互連網開發)2 訪問https介面,進行資料互動(已在實際項目中使用)

來源:互聯網
上載者:User

前言:

      在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 應用新去處贊助支援!!!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.