Preface:
In android development, services with relatively high security, such as banks and online transactions, are involved in https protocol interaction.
The https interaction process is divided into two phases
1. The client obtains the server certificate and verifies whether the certificate content is trusted.
2. handshaking between the client and the server and Data Transmission
For the https interaction process, the first point is to use the website trusted method. If you need to verify that the domain name and certificate are consistent, please expand yourself
Implementation process:
1): Register scheme of https
Note:
HostnameVerifier hostnameVerifier = org. apache. http. conn. ssl. SSLSocketFactory. ALLOW_ALL_HOSTNAME_VERIFIER;
If verification is required, the HostnameVerifier is inherited and the interface is implemented.
2): Get httpClient and httpPost
3): Get Data
The following is the source code, and the parameter is the https path:
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.exe cute (httpPost );
28 if (response. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK ){
29 // parse the returned content
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}
Special thanks:Zhuoyi review network(New places to release Android applications)Sponsorship support !!!