Safe use of HttpURLConnection

后端 未结 7 1762
清歌不尽
清歌不尽 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:26

    You also have to close error stream if the HTTP request fails (anything but 200):

    try {
      ...
    }
    catch (IOException e) {
      connection.getErrorStream().close();
    }
    

    If you don't do it, all requests that don't return 200 (e.g. timeout) will leak one socket.

提交回复
热议问题