目前
HttpWebRequest
我已经为被调用实现了一个简单的辅助方法GetResponse(url)
。目前我在阅读结果后手动关闭WebResponse
and 。StreamReader
然后我像这样返回所说的结果:
// construct the request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
// get the result
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
// clean up and return the result
reader.Close();
response.Close();
return result;
建议的
在语句中包含返回而不是关闭它们是否安全?这会和esusing
有同样的效果吗?.Close()
// construct the request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
// get the result
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}