19

I'd like to use OkHttpClient to load a url, and if the website at the given url responds with a pdf content type I will go ahead and download the PDF, otherwise I want to ignore the response.

My question is, do I need to do anything special to close the request/response or do I need to do anything to indicate that i won't be using the response if I choose to not read the response bytestream? If not, when does OkHttpClient close the connection?

Wise Shepherd
  • 2,228
  • 4
  • 31
  • 43

1 Answers1

36

Calling response.body().close() will release all resources held by the response. The connection pool will keep the connection open, but that'll get closed automatically after a timeout if it goes unused.

ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • Thanks for your answer. Do I need to close the response myself or will the resources automatically be released if I just ignore them? Should I call close on the response even if I do read in the bytestream, after the read of course? Finally, if I call cancel on the request in the on finished callback, will this release the response? – Wise Shepherd Mar 16 '15 at 05:53
  • 4
    In general, you need to close the response. If you read the bytestream to the end, OkHttp will release resources for you, but it's still a good practice to close it anyway. If you cancel the request, you only need to close if `onResponse` gets called. If it doesn't, then we canceled it early enough that there's nothing to close. – Jesse Wilson Mar 17 '15 at 02:46
  • 11
    You can also call `response.close()` which, according to the documentation, is equivalent to `response.body().close()`. – ban-geoengineering Jul 25 '17 at 12:10