I've implemented a simple helper method for HttpWebRequest
called GetResponse(url)
. Currently I'm manually closing the WebResponse
and StreamReader
after reading the result. I'm then returning said result like so:
// 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;
Is it safe to encompass the return within using
statements instead of closing them; will this have the same effect as the .Close()
es?
// 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();
}
}
The browser sends an HTTP request message to the server, asking it to send a copy of the website to the client (you go to the shop and order your goods). This message, and all other data sent between the client and the server, is sent across your internet connection using TCP/IP.
A Stream containing the body of the response.
This is a simple application that the gets the source of a webpage via the WebRequest Object. The WebRequest class is defined in System.Net namespace. WebRequest is an abstract class. It is the base class for accessing data from the internet in the . Net Framework.
That's not only safe - it's safer than the original, in that it will dispose of the objects even if an exception is thrown; a using
statement is equivalent to a try
/finally
statement.
In general, whenever you write a Close()
or Dispose()
call explicitly, consider whether you could use a using
statement instead.
(Note that you're not using the encoding from the web response, by the way - you're always assuming UTF-8. Using WebClient
instead can make this simpler, if that's an option.)
I would suggest do this:
string ret = string.Empty;
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
ret = reader.ReadToEnd();
}
}
return ret;
it is safe to use "using", it will dispose the WebResponse and StreamReader, but it does not guarantee it will run the return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With