gpt4 book ai didi

java - URLConnection 的 getInputStream() 是否每次都返回相同的 InputStream?

转载 作者:行者123 更新时间:2023-11-30 01:16:36 25 4
gpt4 key购买 nike

像这样从 URLConnection 获取 InputStream 是很常见的:

InputStream stream =  connection.getInputStream();

其中连接是一个 URLConnection

https://developer.android.com/reference/java/net/URLConnection.html#getInputStream()

我有一种情况想重用一个流。我可以访问连接对象,我现在的问题是 URLConnection 的单个实例每次都返回“相同”的 InputStream 吗?也就是说,如果我再次调用 connection.getInputStream() (但是对于同一个连接对象)我会得到一个新的流吗?

最佳答案

一般来说,这类问题(“X 做 Y 吗?”)的答案是:文档是否 X 做 Y?如果是这样,是的(或者它坏了);如果不是,您不能保证是,并且必须假设不是。

那么让我们看看URLConnection#getInputStream's documentation :

Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

Returns:

an input stream that reads from this open connection.

所以你不能依赖它这样做,因为它没有 promise 。 (我还在 JavaDoc 的其他地方查找了 URLConnection。)

(我在 Android 之外的测试表明 HttpURLConnection 至少有时会这样做。)

关于java - URLConnection 的 getInputStream() 是否每次都返回相同的 InputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37774375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com