Android okHttp:Https之SSL - Hostname was not verified

欢迎各位访问的博客,博客地址

踩坑篇

项目服务端传输协议换成了https,客户端打接口一直报:Hostname 'url' was not verified
原因:服务端https的证书没有过审
解决方案(直接上代码):

private static void allowAllSSL() {
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }}, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        mOkHttpClient.setSslSocketFactory(sc.getSocketFactory());
        mOkHttpClient.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }

主要是这里:

mOkHttpClient.setSslSocketFactory(sc.getSocketFactory());
        mOkHttpClient.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }

具体分析可以去了解下SSL安全协议,这样写之后实际是降低了https的安全性了,不过证书不过审只能这样了。

发布了82 篇原创文章 · 获赞 152 · 访问量 14万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览