Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."

HOWEVER:

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.

HOWEVER PART2:

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

All Implemented Interfaces: Closeable, AutoCloseable

SUMMARY:

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

What am I missing?

like image 329
Adam Varhegyi Avatar asked Oct 28 '25 10:10

Adam Varhegyi


1 Answers

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.

https://github.com/square/okhttp

compile 'com.squareup.okhttp3:okhttp:3.4.1'
like image 196
Yuri Schimke Avatar answered Oct 29 '25 23:10

Yuri Schimke