Easiest way to read the response from WebResponse

private void RespCallback(IAsyncResult asynchronousResult)
{
    try
    {
        WebRequest myWebRequest1 = (WebRequest)asynchronousResult.AsyncState;

        // End the Asynchronous response.
        WebResponse webResponse = myWebRequest1.EndGetResponse(asynchronousResult);
    }
    catch (Exception)
    {
        // TODO:Log the error
    }
}

Now having the webResponse object, what is the easiest way to read its contents?


Solution 1:

I would simply use the async methods on WebClient - much easier to work with:

        WebClient client = new WebClient();
        client.DownloadStringCompleted += (sender,args) => {
            if(!args.Cancelled && args.Error == null) {
                string result = args.Result; // do something fun...
            }
        };
        client.DownloadStringAsync(new Uri("http://foo.com/bar"));

But to answer the question; assuming it is text, something like (noting you may need to specify the encoding):

        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            string result = reader.ReadToEnd(); // do something fun...
        }

Solution 2:

Here is one way to do it if the response is coming in from XML.

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.yoururl.com");
WebResponse response = myReq.GetResponse();
Stream responseStream = response.GetResponseStream();
XmlTextReader reader = new XmlTextReader(responseStream);
while (reader.Read())
{
    if (reader.NodeType == XmlNodeType.Text)
    {
        Console.WriteLine("{0}", reader.Value.Trim());
    }                       
    Console.ReadLine();
}

Solution 3:

internal string Get(string uri)
{
    using (WebResponse wr = WebRequest.Create(uri).GetResponse())
    {
        using (StreamReader sr = new StreamReader(wr.GetResponseStream()))
        {
            return sr.ReadToEnd();
        }
    }
}