Safe use of HttpURLConnection

后端 未结 7 1785
清歌不尽
清歌不尽 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条回答
  •  旧时难觅i
    2020-11-29 20:15

    Since Java 7 the recommended way is

    try (InputStream is = conn.getInputStream()) {
        // read from is
        // ...
    }
    

    as for all other classes implementing Closable. close() is called at the end of the try {...} block.

    Closing the input stream also means you are done with reading. Otherwise the connection hangs around until the finalizer closes the stream.

    Same applies to the output stream, if you are sending data.

提交回复
热议问题