>>分享Android开发相关的技术 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 22915 个阅读者 刷新本主题
 * 贴子主题:  Android忽略HTTPS安全验证的解决 回复文章 点赞(0)  收藏  
作者:mary    发表时间:2020-03-31 23:49:15     消息  查看  搜索  好友  邮件  复制  引用

          通过Https访问的时候经常会遇到"Not trusted Server Certificate"的问题,有人说在3.0上面没有这个问题,可能已经改进了,在2.2及以前的版本中有这个问题。

         开始想的是采用安装证书的方法(Trusting SSL certificates),最后也没有成功,不知道是证书的原因还是其他,有人说安装证书只能在WIFI上使用,没有找到官方文档,用户可能在GPRS上使用,只能放弃。

         StackOverflow上也有相关的方案,我整理了一下。

         我将注册的步骤封装到DefaultHttpClient子类中了,这样看上去更清晰一些,你也可以

         直接实例化DefaultHttpClient的方法。        
  1.    SchemeRegistry schemeRegistry =  new  SchemeRegistry(); schemeRegistry.register( new  Scheme ( "https" , sslf,  443 ));  
  2.   SingleClientConnManager cm =  new  
  3.   SingleClientConnManager(post.getParams(), schemeRegistry);  
  4.   HttpClient client =  new  DefaultHttpClient(cm, post.getParams());
  1.    /**
  2.     * @author Brant
  3.     * @decription
  4.     */  
  5.    public   class  SSLHttpClient  extends  DefaultHttpClient {
  6.        @Override  
  7.        protected  ClientConnectionManager createClientConnectionManager() {
  8.           SchemeRegistry registry =  new  SchemeRegistry();
  9.           registry.register( new  Scheme( "http" , PlainSocketFactory
  10.                   .getSocketFactory(),  80 ));
            //443是Https的默认端口,如果网站配置的端口不一样,这里要记着改一下
  11.           registry.register( new  Scheme( "https" ,  new  EasySSLSocketFactory(),  443 ));
  12.            return   new  SingleClientConnManager(getParams(), registry);
  13.       }
  14.        public   static  SSLHttpClient getInstance() {
  15.           SSLHttpClient client =  new  SSLHttpClient();
  16.           client.setCookieStore(mCookie);
  17.            return  client;
  18.       }
  19.   }
       EasySSLSocketFactory:        
  1.    import  java.io.IOException;
  2.    import  java.net.InetAddress;
  3.    import  java.net.InetSocketAddress;
  4.    import  java.net.Socket;
  5.    import  java.net.UnknownHostException;
  6.    import  javax.net.ssl.SSLContext;
  7.    import  javax.net.ssl.SSLSocket;
  8.    import  javax.net.ssl.TrustManager;
  9.    import  org.apache.http.conn.ConnectTimeoutException;
  10.    import  org.apache.http.conn.scheme.LayeredSocketFactory;
  11.    import  org.apache.http.conn.scheme.SocketFactory;
  12.    import  org.apache.http.params.HttpConnectionParams;
  13.    import  org.apache.http.params.HttpParams;
  14.    /**
  15.     * This socket factory will create ssl socket that accepts self signed
  16.     * certificate
  17.     *  
  18.     * @author olamy
  19.     * @version $Id: EasySSLSocketFactory.java 765355 2009-04-15 20:59:07Z evenisse
  20.     *          $
  21.     * @since 1.2.3
  22.     */  
  23.    public   class  EasySSLSocketFactory  implements  SocketFactory,
  24.           LayeredSocketFactory {
  25.        private  SSLContext sslcontext =  null ;
  26.        private   static  SSLContext createEasySSLContext()  throws  IOException {
  27.            try  {
  28.               SSLContext context = SSLContext.getInstance( "TLS" );
  29.               context.init( null ,  new  TrustManager[] {  new  EasyX509TrustManager(
  30.                        null ) },  null );
  31.                return  context;
  32.           }  catch  (Exception e) {
  33.                throw   new  IOException(e.getMessage());
  34.           }
  35.       }
  36.        private  SSLContext getSSLContext()  throws  IOException {
  37.            if  ( this .sslcontext ==  null ) {
  38.                this .sslcontext = createEasySSLContext();
  39.           }
  40.            return   this .sslcontext;
  41.       }
  42.        /**
  43.         * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
  44.         *      java.lang.String, int, java.net.InetAddress, int,
  45.         *      org.apache.http.params.HttpParams)
  46.         */  
  47.        public  Socket connectSocket(Socket sock, String host,  int  port,
  48.               InetAddress localAddress,  int  localPort, HttpParams params)
  49.                throws  IOException, UnknownHostException, ConnectTimeoutException {
  50.            int  connTimeout = HttpConnectionParams.getConnectionTimeout(params);
  51.            int  soTimeout = HttpConnectionParams.getSoTimeout(params);
  52.           InetSocketAddress remoteAddress =  new  InetSocketAddress(host, port);
  53.           SSLSocket sslsock = (SSLSocket) ((sock !=  null ) ? sock : createSocket());
  54.            if  ((localAddress !=  null ) || (localPort >  0 )) {
  55.                // we need to bind explicitly  
  56.                if  (localPort <  0 ) {
  57.                   localPort =  0 ;  // indicates "any"  
  58.               }
  59.               InetSocketAddress isa =  new  InetSocketAddress(localAddress,
  60.                       localPort);
  61.               sslsock.bind(isa);
  62.           }
  63.           sslsock.connect(remoteAddress, connTimeout);
  64.           sslsock.setSoTimeout(soTimeout);
  65.            return  sslsock;
  66.       }
  67.        /**
  68.         * @see org.apache.http.conn.scheme.SocketFactory#createSocket()
  69.         */  
  70.        public  Socket createSocket()  throws  IOException {
  71.            return  getSSLContext().getSocketFactory().createSocket();
  72.       }
  73.        /**
  74.         * @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket)
  75.         */  
  76.        public   boolean  isSecure(Socket socket)  throws  IllegalArgumentException {
  77.            return   true ;//不判断socket,直接返回true
  78.       }
  79.        /**
  80.         * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
  81.         *      java.lang.String, int, boolean)
  82.         */  
  83.        public  Socket createSocket(Socket socket, String host,  int  port,
  84.                boolean  autoClose)  throws  IOException, UnknownHostException {
  85.            //return getSSLContext().getSocketFactory().createSocket();
  86.            //will get java.io.IOException: SSL handshake failure: I/O error
  87.            //during system call, Broken pipe
  88.            return  getSSLContext().getSocketFactory().createSocket(socket, host,
  89.                   port, autoClose);
  90.       }
  91.        // -------------------------------------------------------------------  
  92.        // javadoc in org.apache.http.conn.scheme.SocketFactory says :  
  93.        // Both Object.equals() and Object.hashCode() must be overridden  
  94.        // for the correct operation of some connection managers  
  95.        // -------------------------------------------------------------------  
  96.        public   boolean  equals(Object obj) {
  97.            return  ((obj !=  null ) && obj.getClass().equals(
  98.                   EasySSLSocketFactory. class ));
  99.       }
  100.        public   int  hashCode() {
  101.            return  EasySSLSocketFactory. class .hashCode();
  102.       }
  103.   }
      EasyX509TrustManager:        
  1.    import  java.security.KeyStore;
  2.    import  java.security.KeyStoreException;
  3.    import  java.security.NoSuchAlgorithmException;
  4.    import  java.security.cert.CertificateException;
  5.    import  java.security.cert.X509Certificate;
  6.    import  javax.net.ssl.TrustManager;
  7.    import  javax.net.ssl.TrustManagerFactory;
  8.    import  javax.net.ssl.X509TrustManager;
  9.    /**
  10.     * @author olamy
  11.     * @version $Id: EasyX509TrustManager.java 765355 2009-04-15 20:59:07Z evenisse
  12.     *          $
  13.     * @since 1.2.3
  14.     */  
  15.    public   class  EasyX509TrustManager  implements  X509TrustManager {
  16.        private  X509TrustManager standardTrustManager =  null ;
  17.        /**
  18.         * Constructor for EasyX509TrustManager.
  19.         */  
  20.        public  EasyX509TrustManager(KeyStore keystore)
  21.                throws  NoSuchAlgorithmException, KeyStoreException {
  22.            super ();
  23.           TrustManagerFactory factory = TrustManagerFactory
  24.                   .getInstance(TrustManagerFactory.getDefaultAlgorithm());
  25.           factory.init(keystore);
  26.           TrustManager[] trustmanagers = factory.getTrustManagers();
  27.            if  (trustmanagers.length ==  0 ) {
  28.                throw   new  NoSuchAlgorithmException( "no trust manager found" );
  29.           }
  30.            this .standardTrustManager = (X509TrustManager) trustmanagers[ 0 ];
  31.       }
  32.        /**
  33.         * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
  34.         *      String authType)
  35.         */  
  36.        public   void  checkClientTrusted(X509Certificate[] certificates,
  37.               String authType)  throws  CertificateException {
  38.           standardTrustManager.checkClientTrusted(certificates, authType);
  39.       }
  40.        /**
  41.         * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
  42.         *      String authType)
  43.         */  
  44.        public   void  checkServerTrusted(X509Certificate[] certificates,
  45.               String authType)  throws  CertificateException {
  46.            if  ((certificates !=  null ) && (certificates.length ==  1 )) {
  47.               certificates[ 0 ].checkValidity();
  48.           }  else  {
  49.               standardTrustManager.checkServerTrusted(certificates, authType);
  50.           }
  51.       }
  52.        /**
  53.         * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
  54.         */  
  55.        public  X509Certificate[] getAcceptedIssuers() {
  56.            return   this .standardTrustManager.getAcceptedIssuers();
  57.       }
  58.   }
      然后直接实例化SSLHttpClient就可以想Http一样执行HttpGet和HttpPost方法了,希望能有所帮助:)。



----------------------------
原文链接:https://blog.51cto.com/lbrant/795636

程序猿的技术大观园:www.javathinker.net



[这个贴子最后由 flybird 在 2020-04-08 08:22:28 重新编辑]
  Java面向对象编程-->按面向对象开发的基础范例
  JavaWeb开发-->集合(上)
  JSP与Hibernate开发-->Servlet技术详解(Ⅰ)
  Java网络编程-->Web运作原理(Ⅰ)
  精通Spring-->域对象在持久化层的四种状态
  Vue3开发-->第一个helloapp应用
  Android基础之用Eclipse搭建Android开发环境和创建第一个And...
  Android Gallery实现循环显示图像
  Android Broadcast receiver 编程
  Android ExpandableListView 使用范例
  Android 滚动Tab
  编译Irrlicht On Android
  Android UI学习 - Menu
  Android开发实践:Android.mk模板
  Android内核开发:图解Android系统的启动过程
  安卓隐藏标题栏方法
  Scroll的原理和简单使用
  Android性能优化之视图篇(渲染机制)_移动开发_Applicaton的...
  android 拼图小游戏
  怎么让软键盘弹出时,部分控件上移
  Android 之不要滥用 SharedPreferences(下)
  更多...
 IPIP: 已设置保密
树形列表:   
1页 1条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。