HttpsURLConnection内存泄漏

时间:2018-10-22 08:33:31

标签: android httpsurlconnection leakcanary

使用LeakCanary,我发现发生了这样的日志的内存泄漏。

HttpsURLConnection$NoPreloadHolder.defaultHostnameVerifier -> 
MainActivity$16.this$0 -> 
MainActivity

我的代码中唯一提及HttpsUrlConnection的部分是

static SSLContext sc;
private void handleSSLHandshake() {
    try{
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }};

        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }catch (Exception e){
        Log.d(TAG, "handleSSL err: "+e.getMessage());
    }
}

如果我没记错的话,该代码用于使Volley接受https请求。我看到一些帖子说我需要关闭URLConnection,但是HttpsURLConnection没有关闭它的方法。将SSlContext更改为static并没有任何改变。

我在MainActivity的handleSSLHandshake()上致电onCreate()

这是先前的handleSSLHandshake()方法。

private void handleSSLHandshake() {
    try{
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }};

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }catch (Exception e){
        Log.d(TAG, "handleSSL err: "+e.getMessage());
    }
}

2 个答案:

答案 0 :(得分:0)

您需要使用disconnect()方法关闭HttpsUrlConnection

答案 1 :(得分:0)

在SSLContext sc之前删除修饰符为静态。