Android Https请求详细demo

来源:互联网 发布:final java 参数 编辑:程序博客网 时间:2024/06/05 20:56

   Android Https详细请求全方案实现,包括HttpUrlConnection及HttpClient方式实现指定证书及信任所有的实现,不多说了,以下代码都经过详细测试,可以直接使用。

    

Java代码  收藏代码
  1. package com.example.httpstest;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.net.URL;  
  8. import java.security.KeyManagementException;  
  9. import java.security.KeyStore;  
  10. import java.security.KeyStoreException;  
  11. import java.security.NoSuchAlgorithmException;  
  12. import java.security.cert.Certificate;  
  13. import java.security.cert.CertificateException;  
  14. import java.security.cert.CertificateFactory;  
  15. import java.security.cert.X509Certificate;  
  16.   
  17. import javax.net.ssl.HostnameVerifier;  
  18. import javax.net.ssl.HttpsURLConnection;  
  19. import javax.net.ssl.SSLContext;  
  20. import javax.net.ssl.SSLSession;  
  21. import javax.net.ssl.TrustManager;  
  22. import javax.net.ssl.TrustManagerFactory;  
  23. import javax.net.ssl.X509TrustManager;  
  24.   
  25. import org.apache.http.HttpEntity;  
  26. import org.apache.http.HttpResponse;  
  27. import org.apache.http.client.ClientProtocolException;  
  28. import org.apache.http.client.methods.HttpGet;  
  29. import org.apache.http.conn.ClientConnectionManager;  
  30. import org.apache.http.conn.scheme.PlainSocketFactory;  
  31. import org.apache.http.conn.scheme.Scheme;  
  32. import org.apache.http.conn.scheme.SchemeRegistry;  
  33. import org.apache.http.impl.client.DefaultHttpClient;  
  34. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  35. import org.apache.http.params.BasicHttpParams;  
  36. import org.apache.http.params.HttpConnectionParams;  
  37. import org.apache.http.params.HttpParams;  
  38.   
  39. import android.app.Activity;  
  40. import android.os.Bundle;  
  41. import android.util.Log;  
  42.   
  43. /** 
  44.  * HTTPS测试 测试地址:https://certs.cac.washington.edu/CAtest/ 
  45.  * 测试证书:https://www.washington.edu/itconnect/security/ca/load-der.crt 
  46.  *  
  47.  *  
  48.  * @author guojing09 
  49.  *  
  50.  */  
  51. public class MainActivity extends Activity {  
  52.   
  53.     @Override  
  54.     protected void onCreate(Bundle savedInstanceState) {  
  55.         super.onCreate(savedInstanceState);  
  56.         setContentView(R.layout.activity_main);  
  57.         new Thread(new Runnable() {  
  58.   
  59.             @Override  
  60.             public void run() {  
  61.                 try {  
  62.                     initSSLWithHttpClinet();  
  63.                 } catch (Exception e) {  
  64.                     Log.e("HTTPS TEST", e.getMessage());  
  65.                 }  
  66.             }  
  67.         }).start();  
  68.     }  
  69.   
  70.     /** 
  71.      * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议 
  72.      *  
  73.      * @throws CertificateException 
  74.      * @throws IOException 
  75.      * @throws KeyStoreException 
  76.      * @throws NoSuchAlgorithmException 
  77.      * @throws KeyManagementException 
  78.      */  
  79.     public void initSSL() throws CertificateException, IOException, KeyStoreException,  
  80.             NoSuchAlgorithmException, KeyManagementException {  
  81.         CertificateFactory cf = CertificateFactory.getInstance("X.509");  
  82.         InputStream in = getAssets().open("load-der.crt");  
  83.         Certificate ca = cf.generateCertificate(in);  
  84.   
  85.         KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());  
  86.         keystore.load(nullnull);  
  87.         keystore.setCertificateEntry("ca", ca);  
  88.   
  89.         String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();  
  90.         TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);  
  91.         tmf.init(keystore);  
  92.   
  93.         // Create an SSLContext that uses our TrustManager  
  94.         SSLContext context = SSLContext.getInstance("TLS");  
  95.         context.init(null, tmf.getTrustManagers(), null);  
  96.         URL url = new URL("https://certs.cac.washington.edu/CAtest/");  
  97.         HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();  
  98.         urlConnection.setSSLSocketFactory(context.getSocketFactory());  
  99.         InputStream input = urlConnection.getInputStream();  
  100.   
  101.         BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));  
  102.         StringBuffer result = new StringBuffer();  
  103.         String line = "";  
  104.         while ((line = reader.readLine()) != null) {  
  105.             result.append(line);  
  106.         }  
  107.         Log.e("TTTT", result.toString());  
  108.     }  
  109.   
  110.     /** 
  111.      * HttpUrlConnection支持所有Https免验证,不建议使用 
  112.      *  
  113.      * @throws KeyManagementException 
  114.      * @throws NoSuchAlgorithmException 
  115.      * @throws IOException 
  116.      */  
  117.     public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException {  
  118.         URL url = new URL("https://certs.cac.washington.edu/CAtest/");  
  119.         SSLContext context = SSLContext.getInstance("TLS");  
  120.         context.init(nullnew TrustManager[] { new TrustAllManager() }, null);  
  121.         HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());  
  122.         HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {  
  123.   
  124.             @Override  
  125.             public boolean verify(String arg0, SSLSession arg1) {  
  126.                 return true;  
  127.             }  
  128.         });  
  129.         HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();  
  130.         connection.setDoInput(true);  
  131.         connection.setDoOutput(false);  
  132.         connection.setRequestMethod("GET");  
  133.         connection.connect();  
  134.         InputStream in = connection.getInputStream();  
  135.         BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
  136.         String line = "";  
  137.         StringBuffer result = new StringBuffer();  
  138.         while ((line = reader.readLine()) != null) {  
  139.             result.append(line);  
  140.         }  
  141.         Log.e("TTTT", result.toString());  
  142.     }  
  143.       
  144.     /** 
  145.      * HttpClient方式实现,支持所有Https免验证方式链接 
  146.      *  
  147.      * @throws ClientProtocolException 
  148.      * @throws IOException 
  149.      */  
  150.     public void initSSLAllWithHttpClient() throws ClientProtocolException, IOException {  
  151.         int timeOut = 30 * 1000;  
  152.         HttpParams param = new BasicHttpParams();  
  153.         HttpConnectionParams.setConnectionTimeout(param, timeOut);  
  154.         HttpConnectionParams.setSoTimeout(param, timeOut);  
  155.         HttpConnectionParams.setTcpNoDelay(param, true);  
  156.   
  157.         SchemeRegistry registry = new SchemeRegistry();  
  158.         registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
  159.         registry.register(new Scheme("https", TrustAllSSLSocketFactory.getDefault(), 443));  
  160.         ClientConnectionManager manager = new ThreadSafeClientConnManager(param, registry);  
  161.         DefaultHttpClient client = new DefaultHttpClient(manager, param);  
  162.   
  163.         HttpGet request = new HttpGet("https://certs.cac.washington.edu/CAtest/");  
  164.         // HttpGet request = new HttpGet("https://www.alipay.com/");  
  165.         HttpResponse response = client.execute(request);  
  166.         HttpEntity entity = response.getEntity();  
  167.         BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));  
  168.         StringBuilder result = new StringBuilder();  
  169.         String line = "";  
  170.         while ((line = reader.readLine()) != null) {  
  171.             result.append(line);  
  172.         }  
  173.         Log.e("HTTPS TEST", result.toString());  
  174.     }  
  175.   
  176.     /** 
  177.      * HttpClient方式实现,支持验证指定证书 
  178.      *  
  179.      * @throws ClientProtocolException 
  180.      * @throws IOException 
  181.      */  
  182.     public void initSSLCertainWithHttpClient() throws ClientProtocolException, IOException {  
  183.         int timeOut = 30 * 1000;  
  184.         HttpParams param = new BasicHttpParams();  
  185.         HttpConnectionParams.setConnectionTimeout(param, timeOut);  
  186.         HttpConnectionParams.setSoTimeout(param, timeOut);  
  187.         HttpConnectionParams.setTcpNoDelay(param, true);  
  188.   
  189.         SchemeRegistry registry = new SchemeRegistry();  
  190.         registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
  191.         registry.register(new Scheme("https", TrustCertainHostNameFactory.getDefault(this), 443));  
  192.         ClientConnectionManager manager = new ThreadSafeClientConnManager(param, registry);  
  193.         DefaultHttpClient client = new DefaultHttpClient(manager, param);  
  194.   
  195.         // HttpGet request = new  
  196.         // HttpGet("https://certs.cac.washington.edu/CAtest/");  
  197.         HttpGet request = new HttpGet("https://www.alipay.com/");  
  198.         HttpResponse response = client.execute(request);  
  199.         HttpEntity entity = response.getEntity();  
  200.         BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));  
  201.         StringBuilder result = new StringBuilder();  
  202.         String line = "";  
  203.         while ((line = reader.readLine()) != null) {  
  204.             result.append(line);  
  205.         }  
  206.         Log.e("HTTPS TEST", result.toString());  
  207.     }  
  208.   
  209.     public class TrustAllManager implements X509TrustManager {  
  210.   
  211.         @Override  
  212.         public void checkClientTrusted(X509Certificate[] arg0, String arg1)  
  213.                 throws CertificateException {  
  214.             // TODO Auto-generated method stub  
  215.   
  216.         }  
  217.   
  218.         @Override  
  219.         public void checkServerTrusted(X509Certificate[] arg0, String arg1)  
  220.                 throws CertificateException {  
  221.             // TODO Auto-generated method stub  
  222.   
  223.         }  
  224.   
  225.         @Override  
  226.         public X509Certificate[] getAcceptedIssuers() {  
  227.             // TODO Auto-generated method stub  
  228.             return null;  
  229.         }  
  230.     }  
  231.   
  232. }  

 

Java代码  收藏代码
  1. package com.example.httpstest;  
  2.   
  3. import java.io.IOException;  
  4. import java.lang.reflect.Field;  
  5. import java.net.InetAddress;  
  6. import java.net.Socket;  
  7. import java.net.UnknownHostException;  
  8. import java.security.KeyManagementException;  
  9. import java.security.KeyStoreException;  
  10. import java.security.NoSuchAlgorithmException;  
  11. import java.security.UnrecoverableKeyException;  
  12. import java.security.cert.CertificateException;  
  13. import java.security.cert.X509Certificate;  
  14.   
  15. import javax.net.ssl.SSLContext;  
  16. import javax.net.ssl.SSLException;  
  17. import javax.net.ssl.SSLSession;  
  18. import javax.net.ssl.SSLSocket;  
  19. import javax.net.ssl.TrustManager;  
  20. import javax.net.ssl.X509TrustManager;  
  21.   
  22. import org.apache.http.conn.scheme.SocketFactory;  
  23. import org.apache.http.conn.ssl.SSLSocketFactory;  
  24. import org.apache.http.conn.ssl.X509HostnameVerifier;  
  25.   
  26. import android.os.Build;  
  27.   
  28. public class TrustAllSSLSocketFactory extends SSLSocketFactory {  
  29.     private javax.net.ssl.SSLSocketFactory factory;  
  30.     private static TrustAllSSLSocketFactory instance;  
  31.   
  32.     private TrustAllSSLSocketFactory() throws KeyManagementException, UnrecoverableKeyException,  
  33.             NoSuchAlgorithmException, KeyStoreException {  
  34.         super(null);  
  35.   
  36.         SSLContext context = SSLContext.getInstance("TLS");  
  37.         context.init(nullnew TrustManager[] { new TrustAllManager() }, null);  
  38.         factory = context.getSocketFactory();  
  39.         setHostnameVerifier(new X509HostnameVerifier() {  
  40.   
  41.             @Override  
  42.             public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {  
  43.                 // TODO Auto-generated method stub  
  44.   
  45.             }  
  46.   
  47.             @Override  
  48.             public void verify(String host, X509Certificate cert) throws SSLException {  
  49.                 // TODO Auto-generated method stub  
  50.   
  51.             }  
  52.   
  53.             @Override  
  54.             public void verify(String host, SSLSocket ssl) throws IOException {  
  55.                 // TODO Auto-generated method stub  
  56.   
  57.             }  
  58.   
  59.             @Override  
  60.             public boolean verify(String host, SSLSession session) {  
  61.                 // TODO Auto-generated method stub  
  62.                 return true;  
  63.             }  
  64.         });  
  65.     }  
  66.   
  67.     public static SocketFactory getDefault() {  
  68.         if (instance == null) {  
  69.             try {  
  70.                 instance = new TrustAllSSLSocketFactory();  
  71.             } catch (KeyManagementException e) {  
  72.                 // TODO Auto-generated catch block  
  73.                 e.printStackTrace();  
  74.             } catch (UnrecoverableKeyException e) {  
  75.                 // TODO Auto-generated catch block  
  76.                 e.printStackTrace();  
  77.             } catch (NoSuchAlgorithmException e) {  
  78.                 // TODO Auto-generated catch block  
  79.                 e.printStackTrace();  
  80.             } catch (KeyStoreException e) {  
  81.                 // TODO Auto-generated catch block  
  82.                 e.printStackTrace();  
  83.             }  
  84.         }  
  85.         return instance;  
  86.     }  
  87.   
  88.     @Override  
  89.     public Socket createSocket() throws IOException {  
  90.         return factory.createSocket();  
  91.     }  
  92.   
  93.     @Override  
  94.     public Socket createSocket(Socket socket, String host, int port, boolean autoClose)  
  95.             throws IOException, UnknownHostException {  
  96.         if (Build.VERSION.SDK_INT < 11) { // 3.0  
  97.             injectHostname(socket, host);  
  98.         }  
  99.   
  100.         return factory.createSocket(socket, host, port, autoClose);  
  101.     }  
  102.   
  103.     private void injectHostname(Socket socket, String host) {  
  104.         try {  
  105.             Field field = InetAddress.class.getDeclaredField("hostName");  
  106.             field.setAccessible(true);  
  107.             field.set(socket.getInetAddress(), host);  
  108.         } catch (Exception ignored) {  
  109.         }  
  110.     }  
  111.   
  112.     public class TrustAllManager implements X509TrustManager {  
  113.   
  114.         @Override  
  115.         public void checkClientTrusted(X509Certificate[] arg0, String arg1)  
  116.                 throws CertificateException {  
  117.             // TODO Auto-generated method stub  
  118.   
  119.         }  
  120.   
  121.         @Override  
  122.         public void checkServerTrusted(X509Certificate[] arg0, String arg1)  
  123.                 throws CertificateException {  
  124.             // TODO Auto-generated method stub  
  125.   
  126.         }  
  127.   
  128.         @Override  
  129.         public X509Certificate[] getAcceptedIssuers() {  
  130.             // TODO Auto-generated method stub  
  131.             return null;  
  132.         }  
  133.     }  
  134.   
  135. }  

 

Java代码  收藏代码
  1. package com.example.httpstest;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.net.Socket;  
  6. import java.net.UnknownHostException;  
  7. import java.security.KeyManagementException;  
  8. import java.security.KeyStore;  
  9. import java.security.KeyStoreException;  
  10. import java.security.NoSuchAlgorithmException;  
  11. import java.security.UnrecoverableKeyException;  
  12. import java.security.cert.Certificate;  
  13. import java.security.cert.CertificateFactory;  
  14.   
  15. import org.apache.http.conn.ssl.SSLSocketFactory;  
  16.   
  17. import android.content.Context;  
  18.   
  19. public class TrustCertainHostNameFactory extends SSLSocketFactory {  
  20.   
  21.     private static TrustCertainHostNameFactory mInstance;  
  22.   
  23.     public TrustCertainHostNameFactory(KeyStore truststore) throws NoSuchAlgorithmException,  
  24.             KeyManagementException, KeyStoreException, UnrecoverableKeyException {  
  25.         super(truststore);  
  26.     }  
  27.   
  28.     public static TrustCertainHostNameFactory getDefault(Context context) {  
  29.         KeyStore keystore = null;  
  30.         try {  
  31.             CertificateFactory cf = CertificateFactory.getInstance("X.509");  
  32.             InputStream in;  
  33.             in = context.getAssets().open("load-der.crt");  
  34.             Certificate ca = cf.generateCertificate(in);  
  35.   
  36.             keystore = KeyStore.getInstance(KeyStore.getDefaultType());  
  37.             keystore.load(nullnull);  
  38.             keystore.setCertificateEntry("ca", ca);  
  39.   
  40.             if (null == mInstance) {  
  41.                 mInstance = new TrustCertainHostNameFactory(keystore);  
  42.             }  
  43.         } catch (Exception e) {  
  44.   
  45.         }  
  46.         return mInstance;  
  47.     }  
  48.   
  49.     @Override  
  50.     public Socket createSocket() throws IOException {  
  51.         return super.createSocket();  
  52.     }  
  53.   
  54.     @Override  
  55.     public Socket createSocket(Socket socket, String host, int port, boolean autoClose)  
  56.             throws IOException, UnknownHostException {  
  57.         return super.createSocket(socket, host, port, autoClose);  
  58.     }  
  59.   
  60. }  
0 0
原创粉丝点击