【发布时间】:2018-04-29 19:28:29
【问题描述】:
在开发我的 android 应用程序时,我在 Logcat 中收到此警告
WARNING: A connection to https://... was leaked. Did you forget to close a response body?
我使用 Okhttps 作为 volley 的传输层进行网络调用。
class OkHttpStack extends HurlStack {
private final OkUrlFactory okUrlFactory;
OkHttpStack() {
this(new OkUrlFactory(new OkHttpClient()));
}
private OkHttpStack(OkUrlFactory okUrlFactory) {
if (okUrlFactory == null) {
throw new NullPointerException("Client must not be null.");
}
this.okUrlFactory = okUrlFactory;
}
@Override
protected HttpURLConnection createConnection(URL url) throws
IOException {
return okUrlFactory.open(url);
}
}
用于创建请求队列
synchronized RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext,new OkHttpStack());
}
return mRequestQueue;
}
<T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
我这样调用url
public void postCall(final String Url, JSONObject Data, final ResponseCallback responseCallback){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(mUrl+Url, Data,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG,response.toString());
responseCallback.onGettingResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,error.toString());
responseCallback.onError(error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
TIMEOUT_IN_SECONDS,
0,
0));
mRestApiCall.getInstance(mContext).addToRequestQueue(jsonObjectRequest.setTag(mRequestTag));
}
从 Okhttp 问题跟踪器中,我读到我们必须每次都关闭响应主体以避免泄漏,但我不知道在使用 volley 和 Okhttp 时如何做到这一点。
依赖:
compile 'com.android.volley:volley:1.0.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.4.0'
【问题讨论】:
-
请删除 http 日志记录,这是导致此问题的原因之一
标签: android memory-leaks android-volley okhttp okhttp3