当我提前关闭 HttpWebResponse 时 Streamreader 无法工作

发布于 2024-10-05 20:52:05 字数 708 浏览 2 评论 0原文

Uri targetUri = new Uri(targetURL);    
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();
response.Close();

为什么上面的代码可以正常工作,但下面的代码却不行? 请注意,我在以下代码中提前关闭了响应。

Uri targetUri = new Uri(targetURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
response.Close();
string data = reader.ReadToEnd();
Uri targetUri = new Uri(targetURL);    
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();
response.Close();

Why does the above code work fine but the following does not?
Notice I close response early in the following code.

Uri targetUri = new Uri(targetURL);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
response.Close();
string data = reader.ReadToEnd();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

毅然前行 2024-10-12 20:52:05

关闭响应也会关闭响应流...因此 StreamReader 不再有任何内容可供读取。

来自 WebResponse.Close

Close 方法清理
WebResponse 使用的资源和
关闭底层流
调用 Stream.Close 方法。

Closing the response closes the response stream as well... so the StreamReader no longer has anything to read from.

From the documentation for WebResponse.Close:

The Close method cleans up the
resources used by a WebResponse and
closes the underlying stream by
calling the Stream.Close method.

ぺ禁宫浮华殁 2024-10-12 20:52:05

您的阅读器是使用响应中的流进行初始化的,因此它正在使用它。

如果关闭响应流,读取器将不再有可供读取的工作基础流。

Your reader was initialized with the stream from the response, so it is using it.

If you close the response stream, the reader no longer has a working underlying stream to read from.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文