Safe use of HttpURLConnection

后端 未结 7 1768
清歌不尽
清歌不尽 2020-11-29 19:33

When using HttpURLConnection does the InputStream need to be closed if we do not \'get\' and use it?

i.e. is this safe?

HttpURLConnection conn = (Htt         


        
7条回答
  •  隐瞒了意图╮
    2020-11-29 20:15

    If you really want to make sure that the connection is close you should call conn.disconnect().

    The open connections you observed are because of the HTTP 1.1 connection keep alive feature (also known as HTTP Persistent Connections). If the server supports HTTP 1.1 and does not send a Connection: close in the response header Java does not immediately close the underlaying TCP connection when you close the input stream. Instead it keeps it open and tries to reuse it for the next HTTP request to the same server.

    If you don't want this behaviour at all you can set the system property http.keepAlive to false:

    System.setProperty("http.keepAlive","false");
    

提交回复
热议问题