我正在用C#创建HTTP WebRequests来浏览一个网站。我创建请求,获取响应并将其读入StreamReader。然后我使用相同的请求变量创建新请求并获得新响应...
以下是我的代码:
HttpWebRequest request;
WebResponse response;
Stream responseStream;
StreamReader reader;
string responseFromServer;
request = (HttpWebRequest)WebRequest.Create("https://www.firstRequest.com");
//set cookies and headers here...
response = request.GetResponse();
responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);
responseFromServer = reader.ReadToEnd();
//second request using the same variables
request = (HttpWebRequest)WebRequest.Create("https://www.secondRequest.com");
response = request.GetResponse();
responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);
responseFromServer = reader.ReadToEnd();
我知道我必须关闭响应,流和流阅读器以释放资源。我是不是需要在每个请求之间这样做,还是只需要在一切结束时这样做?