当我提前关闭 HttpWebResponse 时 Streamreader 无法工作
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关闭响应也会关闭响应流...因此 StreamReader 不再有任何内容可供读取。
来自
WebResponse.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
:您的阅读器是使用响应中的流进行初始化的,因此它正在使用它。
如果关闭响应流,读取器将不再有可供读取的工作基础流。
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.