简体   繁体   中英

Do I need close inputStream after using getResponseCode (HttpUrlConnection)

do I need to close inputStream when I only checking the response code like below?

    URL u = new URL(url);
    HttpUrlConnection con = (HttpUrlConnection) url.openConnection();
    int statusCode;
    try {
        statusCode = con.getResponseCode();
    } catch(Exception ex){}

No, but ...
Java has a Garbage Collector.
This means: Java will destroy objects when no active thread has a reference to it.
If a thread leaving a method, then all objects will be removed from RAM soon.

But ... it is cleaner to close them directly. It is nicer to read.
And in some cases a explicit closing is necessary. Otherwise it is possible that system-resources are "blocked forever" - but it hardly depends on the implementation of the used libraries.

As a client of a server http, when you close the connection, you close the link between your client and the server http.

So for a best practice, close the connection.

The server can catch a Broken Pipe exception if the request is closed by the client when the server has not yet return the response, and then, the server can manage the closed connection requested by the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM