Adam Varhegyi Adam Varhegyi - 1 year ago 91
Android Question

Trying to close OkHttp's Response but AutoCloseable interface is missing

I use OkHttp network library for my Android project.

Version in Gradle file:

compile 'com.squareup.okhttp:okhttp:2.7.5'

I had a memory leak issue and I have found that I used incorrectly the lib because I didn't closed the ResponseBody object I got from a call.

At Okhttp's github page there is a doc that clarifies:

"The response body must be closed."

It is also gives examples how should I do it (by using AutoCloseable interface with try's syntax):

Call call = client.newCall(request);
try (Response response = call.execute()) {
... // Use the response.

And also:

"Both this class (ResponseBody) and Response implement Closeable. Closing a response simply closes its response body."


If I try to run this code I got:

Incompatible types.

Required: java.lang.AutoCloseable

Found: com.squareup.okhttp.Response

And as I look up com.squareup.okhttp.Response's implementation IN my project I can clearly see that Response doesn't implement any interface.


If I look up Response at OkHttp's docs there is:

All Implemented Interfaces: Closeable, AutoCloseable


Doc says that I can use AutoCloseable but Response class not implementing AutoCloseable.

What am I missing?

Answer Source

The docs you link to are for version 3. Which even has a different package and maven group. Upgrade to version 3.4.1 if you can and see if it fixes your issue.

compile 'com.squareup.okhttp3:okhttp:3.4.1'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download