需要在使用完`getResponseCode`(HttpUrlConnection)之后关闭`inputStream`吗?

huangapple go评论105阅读模式
英文:

Do I need close inputStream after using getResponseCode (HttpUrlConnection)

问题

以下是您要翻译的内容:

我在只检查下面这样的响应代码时,是否需要关闭inputStream?

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

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){}

答案1

得分: 1

不过,Java拥有垃圾回收器。
这意味着:当没有活动线程引用对象时,Java将销毁这些对象。
如果线程离开一个方法,那么所有对象很快将从内存中移除。

但是... 直接关闭它们会更加清晰。这样更易于阅读。
在某些情况下,需要显式关闭。否则,系统资源可能会被“永久阻塞”,但这在很大程度上取决于所使用的库的实现。

英文:

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.

答案2

得分: 0

作为服务器HTTP的客户端,在您关闭连接时,您关闭了客户端和服务器HTTP之间的链接。

因此,按照最佳实践,关闭连接。

如果客户端在服务器尚未返回响应时关闭请求,服务器可以捕获Broken Pipe异常,然后服务器可以处理客户端请求的已关闭连接。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月28日 06:53:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64564071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定