Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to read the response from WebResponse

Tags:

c#

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?

like image 417
Stacker Avatar asked Dec 26 '10 11:12

Stacker


People also ask

What is HttpWebResponse C#?

GetResponseStream Method (System.Net) Gets the stream that is used to read the body of the response from the server.


1 Answers

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...         } 
like image 117
Marc Gravell Avatar answered Oct 12 '22 10:10

Marc Gravell