ESA2GJK1DH1K安全篇: Android以SSL方式连接MQTT服务器

2020-02-17 11:47:24 浏览数 (1)

------------恢复内容开始------------

不导入证书方式

  1.增加以下代码

代码语言:javascript复制
    static class miTM implements TrustManager, X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public boolean isServerTrusted(X509Certificate[] certs) {
            return true; }
        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }
        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException { return; }
        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException { return; }
    }
代码语言:javascript复制
        try{
            TrustManager[] trustAllCerts = new TrustManager[1];
            TrustManager tm = new miTM();
            trustAllCerts[0] = tm;
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, null);
            SocketFactory factory = sc.getSocketFactory();
            mqttConnectOptions.setSocketFactory(factory);
        }catch (Exception e){
            Log.e(TAG, e.toString() );
        }

2.具体添加的位置

3.修改为SSL连接,端口号改为8883

4.测试

------------恢复内容结束------------

0 人点赞