Read text from HTTP response

    HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;  

    request .Accept = "application/xrds+xml";  
    HttpWebResponse response = (HttpWebResponse)request .GetResponse();  

 WebHeaderCollection header= response.Headers;  

Here google returns text. How to read it?

After removing that, you can access the response using response.GetResponseStream().

        HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;

        //request.Accept = "application/xrds+xml";  
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        WebHeaderCollection header = response.Headers;

        var encoding = ASCIIEncoding.ASCII;
        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
        {
            string responseText = reader.ReadToEnd();
        }

OR

using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Web;

class Test
{
    static void Main()
    {
        string url = "http://google.com/xrds/xrds.xml";
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);

        XDocument doc;
        using (WebResponse response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                doc = XDocument.Load(stream);
            }
        }
        // Now do whatever you want with doc here
        Console.WriteLine(doc);
    }   
}

The accepted answer does not correctly dispose the WebResponse or decode the text. Also, there’s a new way to do this in .NET 4.5. A lot of people don’t seem to correctly decode the text, too.

To perform an HTTP GET and read the response text, do the following.

.NET 1.1 ‒ 4.0

public string GetResponseText(string address)
{
    var request = (HttpWebRequest)WebRequest.Create(address);

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        var encoding = Encoding.GetEncoding(response.CharacterSet);

        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream, encoding))
            return reader.ReadToEnd();
    }
}

.NET 4.5

public async Task<string> GetResponseText(string address)
{
    using (var httpClient = new HttpClient())
        return await httpClient.GetStringAsync(address));
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s