While developing my android application I'm getting this warning in my Logcat
WARNING: A connection to https://... was leaked. Did you forget to close a response body?
I'm using Okhttps as a transport layer for the volley for network calling.
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);
}
}
For creating requestQueue
synchronized RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext,new OkHttpStack());
}
return mRequestQueue;
}
<T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
I'm calling url like this
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));
}
From Okhttp issues tracker, I read that We have to close the response body each time to avoid leak but I don't get it how to do this while using volley and Okhttp.
Dependencies :
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'