4

When creating HTTPURLConnection's from android, does anyone have any experience on when to close a connection vs. when to disconnect from a connection? Should disconnect always be used so the connections can be reused from a pool rather than being recreated? And are there any implications/side effects to using disconnect vs. close? The android documentation seems vague in this area....

user207421
  • 305,947
  • 44
  • 307
  • 483
qbert
  • 53
  • 1
  • 4
  • Possible duplicate of [Java HttpURLConnection and pooling](https://stackoverflow.com/questions/35208950/java-httpurlconnection-and-pooling) – user207421 Mar 26 '18 at 03:45

1 Answers1

3

I think you should always call disconnect in the finally block. The android documentation notes that you should use disconnect which facilitates the reuse of the underlying socket if possible. From http://developer.android.com/reference/java/net/HttpURLConnection.html

"Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused."

Nagesh Susarla
  • 1,660
  • 10
  • 10
  • @qbert Call `close()` on a connection how? There is no `HttpURLConnection.close()` method. You have to close the input stream, but that may or may not close the underlying connection. – user207421 Mar 26 '18 at 03:40
  • 2
    This answer is not correct, and neither is the Javadoc quoted. The Javadoc goes on to say that `disconnect()` 'indicates that other requests to the server are unlikely in the near future.' In other words it *closes* the connection, and if you *don't* call it the connection can be pooled. – user207421 Mar 26 '18 at 03:42