android https安全连接

如果不需要验证服务器端证书,直接照这里做

[java] view plaincopy
  1. public class Demo extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.         private TextView text;  
  4.     @Override  
  5.     public void onCreate(Bundle savedInstanceState) {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.main);  
  8.         text = (TextView)findViewById(R.id.text);  
  9.         GetHttps();  
  10.     }  
  11.       
  12.     private void GetHttps(){  
  13.             String https = " https://800wen.com/";  
  14.             try{  
  15.                     SSLContext sc = SSLContext.getInstance("TLS");  
  16.                     sc.init(nullnew TrustManager[]{new MyTrustManager()}, new SecureRandom());  
  17.                     HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
  18.                     HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());  
  19.                     HttpsURLConnection conn = (HttpsURLConnection)new URL(https).openConnection();  
  20.                     conn.setDoOutput(true);  
  21.                     conn.setDoInput(true);  
  22.                     conn.connect();  
  23.                       
  24.                      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));   
  25.              StringBuffer sb = new StringBuffer();   
  26.              String line;   
  27.              while ((line = br.readLine()) != null)   
  28.                      sb.append(line);   
  29.                       
  30.                     text.setText(sb.toString());  
  31.                       
  32.             }catch(Exception e){  
  33.                     Log.e(this.getClass().getName(), e.getMessage());  
  34.             }  
  35.               
  36.     }  
  37.       
  38.     private class MyHostnameVerifier implements HostnameVerifier{  
  39.   
  40.                 @Override  
  41.                 public boolean verify(String hostname, SSLSession session) {  
  42.                         // TODO Auto-generated method stub  
  43.                         return true;  
  44.                 }  
  45.     }  
  46.       
  47.     private class MyTrustManager implements X509TrustManager{  
  48.   
  49.                 @Override  
  50.                 public void checkClientTrusted(X509Certificate[] chain, String authType)  
  51.                                 throws CertificateException {  
  52.                         // TODO Auto-generated method stub  
  53.                           
  54.                 }  
  55.   
  56.                 @Override  
  57.                 public void checkServerTrusted(X509Certificate[] chain, String authType)  
  58.                                 throws CertificateException {  
  59.                         // TODO Auto-generated method stub  
  60.                           
  61.                 }  
  62.   
  63.                 @Override  
  64.                 public X509Certificate[] getAcceptedIssuers() {  
  65.                         // TODO Auto-generated method stub  
  66.                         return null;  
  67.                 }          
  68.     }    
  69. }  

如果需要验证服务器端证书(这样能够防钓鱼),我是这样做的,还有些问题问大牛:
    a. 导出公钥。在浏览器上用https访问tomcat,查看其证书,并另存为一个文件(存成了X.509格式:xxxx.cer)
    b. 导入公钥。把xxxx.cer放在Android的assets文件夹中,以方便在运行时通过代码读取此证书,留了两个问题给大牛:

[java] view plaincopy
  1. AssetManager am = context.getAssets();  
  2. InputStream ins = am.open("robusoft.cer");  
  3. try {  
  4.         //读取证书  
  5.         CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");  //问1  
  6.         Certificate cer = cerFactory.generateCertificate(ins);  
  7.         //创建一个证书库,并将证书导入证书库  
  8.         KeyStore keyStore = KeyStore.getInstance("PKCS12""BC");   //问2  
  9.         keyStore.load(nullnull);  
  10.         keyStore.setCertificateEntry("trust", cer);  
  11.         return keyStore;  
  12. finally {  
  13.         ins.close();  
  14. }  
  15. //把咱的证书库作为信任证书库  
  16. SSLSocketFactory socketFactory = new SSLSocketFactory(keystore);  
  17. Scheme sch = new Scheme("https", socketFactory, 443);  
  18. //完工  
  19. HttpClient mHttpClient = new DefaultHttpClient();  
  20. mHttpClient.getConnectionManager().getSchemeRegistry().register(sch);  

问1:这里用"PKCS12"不行

答1:PKCS12和JKS是keystore的type,不是Certificate的type,所以X.509不能用PKCS12代替


问2:这里用"JKS"不行。

答2:android平台上支持的keystore type好像只有PKCS12,不支持JKS,所以不能用JKS代替在PKCS12,不过在windows平台上是可以代替的


----------------------------------------------分割线-------------------------------------------------------------------------

1。数据通信时加密,不同平台加密后的结果不同,用的库不同吧(进行相应的修改比较麻烦)

2。采用https,系统自动做好了,简单一些

https与http的通信,在我看来主要的区别在于https多了一个安全验证机制,而Android采用的是X509验证,首先我们需要这重写X509类,建立我们的验证规则、、不过对于特定的项目,我们一般都是无条件信任服务端的,因此我们可以对任何证书都无条件信任(其实本质上我们只是信任了特定url的证书,为了偷懒,才那么选择的)/**

 
  1.  * 信任所有主机-对于任何证书都不做检查   
  2.  */   
  3. class MytmArray implements X509TrustManager {   
  4.     public X509Certificate[] getAcceptedIssuers() {   
  5.         // return null;   
  6.         return new X509Certificate[] {};   
  7.     }   
  8.   
  9.     @Override  
  10.     public void checkClientTrusted(X509Certificate[] chain, String authType)   
  11.             throws CertificateException {   
  12.         // TODO Auto-generated method stub   
  13.   
  14.     }   
  15.   
  16.     @Override  
  17.     public void checkServerTrusted(X509Certificate[] chain, String authType)   
  18.             throws CertificateException {   
  19.         // TODO Auto-generated method stub   
  20.         // System.out.println("cert: " + chain[0].toString() + ", authType: "   
  21.         // + authType);   
  22.     }   
  23. };  
[java] view plaincopy
  1.  * 信任所有主机-对于任何证书都不做检查  
  2.  */  
  3. class MytmArray implements X509TrustManager {  
  4.     public X509Certificate[] getAcceptedIssuers() {  
  5.         // return null;  
  6.         return new X509Certificate[] {};  
  7.     }  
  8.   
  9.     @Override  
  10.     public void checkClientTrusted(X509Certificate[] chain, String authType)  
  11.             throws CertificateException {  
  12.         // TODO Auto-generated method stub  
  13.   
  14.     }  
  15.   
  16.     @Override  
  17.     public void checkServerTrusted(X509Certificate[] chain, String authType)  
  18.             throws CertificateException {  
  19.         // TODO Auto-generated method stub  
  20.         // System.out.println("cert: " + chain[0].toString() + ", authType: "  
  21.         // + authType);  
  22.     }  
  23. };  

 好了,我们写好了信任规则,接下载就要创建一个主机的信任列表

 
  1. static TrustManager[] xtmArray = new MytmArray[] { new MytmArray() };   
  2.   
  3.     /**  
  4.      * 信任所有主机-对于任何证书都不做检查  
  5.      */  
  6.     private static void trustAllHosts() {   
  7.         // Create a trust manager that does not validate certificate chains   
  8.         // Android 采用X509的证书信息机制   
  9.         // Install the all-trusting trust manager   
  10.         try {   
  11.             SSLContext sc = SSLContext.getInstance("TLS");   
  12.             sc.init(null, xtmArray, new java.security.SecureRandom());   
  13.             HttpsURLConnection   
  14.                     .setDefaultSSLSocketFactory(sc.getSocketFactory());   
  15.             // HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY);//   
  16.             // 不进行主机名确认   
  17.         } catch (Exception e) {   
  18.             e.printStackTrace();   
  19.         }   
  20.     }   
  21.   
  22.     static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {   
  23.         @Override  
  24.         public boolean verify(String hostname, SSLSession session) {   
  25.             // TODO Auto-generated method stub   
  26.             // System.out.println("Warning: URL Host: " + hostname + " vs. "   
  27.             // + session.getPeerHost());   
  28.             return true;   
  29.         }   
  30.     };  
[java] view plaincopy
  1. static TrustManager[] xtmArray = new MytmArray[] { new MytmArray() };  
  2.   
  3.     /** 
  4.      * 信任所有主机-对于任何证书都不做检查 
  5.      */  
  6.     private static void trustAllHosts() {  
  7.         // Create a trust manager that does not validate certificate chains  
  8.         // Android 采用X509的证书信息机制  
  9.         // Install the all-trusting trust manager  
  10.         try {  
  11.             SSLContext sc = SSLContext.getInstance("TLS");  
  12.             sc.init(null, xtmArray, new java.security.SecureRandom());  
  13.             HttpsURLConnection  
  14.                     .setDefaultSSLSocketFactory(sc.getSocketFactory());  
  15.             // HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY);//  
  16.             // 不进行主机名确认  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21.   
  22.     static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {  
  23.         @Override  
  24.         public boolean verify(String hostname, SSLSession session) {  
  25.             // TODO Auto-generated method stub  
  26.             // System.out.println("Warning: URL Host: " + hostname + " vs. "  
  27.             // + session.getPeerHost());  
  28.             return true;  
  29.         }  
  30.     };  

 上面的都是https通信需要做的几个基本要求,接下载我们要做的就是https的使用啦下面就以get和post为例进行说明,中间还涉及到cookie的使用

 
  1. String httpUrl="XXXXX"  
  2. String result = "";   
  3.         HttpURLConnection http = null;   
  4.         URL url;   
  5.         try {   
  6.             url = new URL(httpUrl);   
  7.             // 判断是http请求还是https请求   
  8.             if (url.getProtocol().toLowerCase().equals("https")) {   
  9.                 trustAllHosts();   
  10.                 http = (HttpsURLConnection) url.openConnection();   
  11.                 ((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认   
  12.   
  13.             } else {   
  14.                 http = (HttpURLConnection) url.openConnection();   
  15.             }   
  16.             http.setConnectTimeout(10000);// 设置超时时间   
  17.             http.setReadTimeout(50000);   
  18.             http.setRequestMethod("GET");// 设置请求类型为   
  19.             http.setDoInput(true);   
  20.             http.setRequestProperty("Content-Type""text/xml");   
  21. //http.getResponseCode());http或https返回状态200还是403   
  22. BufferedReader in = null;   
  23.             if (obj.getHttpStatus() == 200) {   
  24.                 getCookie(http);   
  25.                 in = new BufferedReader(new InputStreamReader(   
  26.                         http.getInputStream()));   
  27.             } else  
  28.                 in = new BufferedReader(new InputStreamReader(   
  29.                         http.getErrorStream()));   
  30.             result = in.readLine();   
  31.             Log.i("result", result);   
  32.             in.close();   
  33.             http.disconnect();  
[java] view plaincopy
  1. String httpUrl="XXXXX"  
  2. String result = "";  
  3.         HttpURLConnection http = null;  
  4.         URL url;  
  5.         try {  
  6.             url = new URL(httpUrl);  
  7.             // 判断是http请求还是https请求  
  8.             if (url.getProtocol().toLowerCase().equals("https")) {  
  9.                 trustAllHosts();  
  10.                 http = (HttpsURLConnection) url.openConnection();  
  11.                 ((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认  
  12.   
  13.             } else {  
  14.                 http = (HttpURLConnection) url.openConnection();  
  15.             }  
  16.             http.setConnectTimeout(10000);// 设置超时时间  
  17.             http.setReadTimeout(50000);  
  18.             http.setRequestMethod("GET");// 设置请求类型为  
  19.             http.setDoInput(true);  
  20.             http.setRequestProperty("Content-Type""text/xml");  
  21. //http.getResponseCode());http或https返回状态200还是403  
  22. BufferedReader in = null;  
  23.             if (obj.getHttpStatus() == 200) {  
  24.                 getCookie(http);  
  25.                 in = new BufferedReader(new InputStreamReader(  
  26.                         http.getInputStream()));  
  27.             } else  
  28.                 in = new BufferedReader(new InputStreamReader(  
  29.                         http.getErrorStream()));  
  30.             result = in.readLine();  
  31.             Log.i("result", result);  
  32.             in.close();  
  33.             http.disconnect();  

 https或http的get请求写好了,哦中间涉及到了一个getCookie的方法,如下:

 
  1. /** 得到cookie */  
  2.     private static void getCookie(HttpURLConnection http) {   
  3.         String cookieVal = null;   
  4.         String key = null;   
  5.         DataDefine.mCookieStore = "";   
  6.         for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++) {   
  7.             if (key.equalsIgnoreCase("set-cookie")) {   
  8.                 cookieVal = http.getHeaderField(i);   
  9.                 cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));   
  10.                 DataDefine.mCookieStore = DataDefine.mCookieStore + cookieVal   
  11.                         + ";";   
  12.             }   
  13.         }   
  14.     }  
[java] view plaincopy
  1. /** 得到cookie */  
  2.     private static void getCookie(HttpURLConnection http) {  
  3.         String cookieVal = null;  
  4.         String key = null;  
  5.         DataDefine.mCookieStore = "";  
  6.         for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++) {  
  7.             if (key.equalsIgnoreCase("set-cookie")) {  
  8.                 cookieVal = http.getHeaderField(i);  
  9.                 cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));  
  10.                 DataDefine.mCookieStore = DataDefine.mCookieStore + cookieVal  
  11.                         + ";";  
  12.             }  
  13.         }  
  14.     }  
 public static Query HttpQueryReturnClass(String httpUrl, String base64) {
 
  1.         String result = "";   
  2.         Log.i("控制", httpUrl);   
  3.         Query obj = new Query();   
  4.         HttpURLConnection http = null;   
  5.         URL url;   
  6.         try {   
  7.             url = new URL(httpUrl);   
  8.             // 判断是http请求还是https请求   
  9.             if (url.getProtocol().toLowerCase().equals("https")) {   
  10.                 trustAllHosts();   
  11.                 http = (HttpsURLConnection) url.openConnection();   
  12.                 ((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认   
  13.             } else {   
  14.                 http = (HttpURLConnection) url.openConnection();   
  15.             }   
  16.             http.setConnectTimeout(10000);// 设置超时时间   
  17.             http.setReadTimeout(50000);   
  18.             http.setRequestMethod("POST");// 设置请求类型为post   
  19.             http.setDoInput(true);   
  20.             http.setDoOutput(true);   
  21.             http.setRequestProperty("Content-Type""text/xml");   
  22.             http.setRequestProperty("Cookie", DataDefine.mCookieStore);   
  23.             DataOutputStream out = new DataOutputStream(http.getOutputStream());   
  24.             out.writeBytes(base64);   
  25.             out.flush();   
  26.             out.close();   
  27.             obj.setHttpStatus(http.getResponseCode());// 设置http返回状态200还是403   
  28.             BufferedReader in = null;   
  29.             if (obj.getHttpStatus() == 200) {   
  30.                 getCookie(http);   
  31.                 in = new BufferedReader(new InputStreamReader(   
  32.                         http.getInputStream()));   
  33.             } else  
  34.                 in = new BufferedReader(new InputStreamReader(   
  35.                         http.getErrorStream()));   
  36.             result = in.readLine();// 得到返回结果   
  37.             in.close();   
  38.             http.disconnect();   
  39.         } catch (Exception e) {   
  40.             // TODO Auto-generated catch block   
  41.             e.printStackTrace();   
  42.         }   
  43. }  
[java] view plaincopy
  1.         String result = "";  
  2.         Log.i("控制", httpUrl);  
  3.         Query obj = new Query();  
  4.         HttpURLConnection http = null;  
  5.         URL url;  
  6.         try {  
  7.             url = new URL(httpUrl);  
  8.             // 判断是http请求还是https请求  
  9.             if (url.getProtocol().toLowerCase().equals("https")) {  
  10.                 trustAllHosts();  
  11.                 http = (HttpsURLConnection) url.openConnection();  
  12.                 ((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认  
  13.             } else {  
  14.                 http = (HttpURLConnection) url.openConnection();  
  15.             }  
  16.             http.setConnectTimeout(10000);// 设置超时时间  
  17.             http.setReadTimeout(50000);  
  18.             http.setRequestMethod("POST");// 设置请求类型为post  
  19.             http.setDoInput(true);  
  20.             http.setDoOutput(true);  
  21.             http.setRequestProperty("Content-Type""text/xml");  
  22.             http.setRequestProperty("Cookie", DataDefine.mCookieStore);  
  23.             DataOutputStream out = new DataOutputStream(http.getOutputStream());  
  24.             out.writeBytes(base64);  
  25.             out.flush();  
  26.             out.close();  
  27.             obj.setHttpStatus(http.getResponseCode());// 设置http返回状态200还是403  
  28.             BufferedReader in = null;  
  29.             if (obj.getHttpStatus() == 200) {  
  30.                 getCookie(http);  
  31.                 in = new BufferedReader(new InputStreamReader(  
  32.                         http.getInputStream()));  
  33.             } else  
  34.                 in = new BufferedReader(new InputStreamReader(  
  35.                         http.getErrorStream()));  
  36.             result = in.readLine();// 得到返回结果  
  37.             in.close();  
  38.             http.disconnect();  
  39.         } catch (Exception e) {  
  40.             // TODO Auto-generated catch block  
  41.             e.printStackTrace();  
  42.         }  
  43. }  
 这里面的base64是我经过base64加密过以后的数据
上一篇:《编写高质量Python代码的59个有效方法》——第14条:尽量用异常来表示特殊情况,而不要返回None


下一篇:一篇文章玩转阿里云日志服务查询分析控制台