使用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());
}
}