84
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?

budi
  • 6,351
  • 10
  • 55
  • 80
Niraj Choubey
  • 3,942
  • 18
  • 58
  • 93

7 Answers7

142

Your "application/xrds+xml" was giving me issues, I was receiving a Content-Length of 0 (no response).

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();
}
budi
  • 6,351
  • 10
  • 55
  • 80
STW
  • 44,917
  • 17
  • 105
  • 161
  • 11
    Note that this is assuming an ASCII encoding, which may well be incorrect. – Jon Skeet Jul 17 '10 at 21:41
  • 1
    Note also that the `WebHeaderCollection` line is not necessary to retrieve the response text. – Sam Feb 09 '13 at 03:28
  • 1
    Note also that the HTTP response is not wrapped in a using block. If an exception or return occurs between the response and the next using block, the connection won't be closed. – Sam Feb 09 '13 at 04:07
  • @Sam thanks for the many edit attempts, however I'm concerned that the result of your edits were largely downvoted by many users (6 in several hours). I've reverted your changes and will try to improve the answer as well. – STW Feb 11 '13 at 15:46
  • I do have a result, which contains `HttpResponseContext`, but I am unable to read the text in to the object(understandable format) Eg: `HttpResponseMessage response = wc.GetAsync(URI).Result;` `var contents = response.Content.ReadAsStringAsync();` here `contents` variable contains some random data instead of required data. – Krish Sep 14 '17 at 10:10
  • (I know this is an old answer but this may help someone in the future) `ReadAsStringAsync` returns a `Task`, you will need to `await` the task completion before accessing the contents. – mattumotu Sep 10 '19 at 09:14
85

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.

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

.NET 1.1 ‒ 4.0

public static 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

private static readonly HttpClient httpClient = new HttpClient();

public static async Task<string> GetResponseText(string address)
{
    return await httpClient.GetStringAsync(address);
}
Sam
  • 40,644
  • 36
  • 176
  • 219
  • i assume you should replace `"http://google.com"` with the parameter name `address`? – Ian Boyd May 20 '13 at 15:26
  • i like this answer, a lot. It's so concise and to the point. And it handles encoding correctly; unlike the accepted answer. It also shows how to access the response *text*, also unlike the accepted answer. – Ian Boyd May 21 '13 at 15:26
  • This code produces a deadlock for me, as described in https://stackoverflow.com/a/10369275/1636247. It needs .GetStringAsync(address).ConfigureAwait(false); before it works. – Harmen Nov 27 '20 at 23:16
11

I've just tried that myself, and it gave me a 200 OK response, but no content - the content length was 0. Are you sure it's giving you content? Anyway, I'll assume that you've really got content.

Getting actual text back relies on knowing the encoding, which can be tricky. It should be in the Content-Type header, but then you've got to parse it etc.

However, if this is actually XML (e.g. from "http://google.com/xrds/xrds.xml"), it's a lot easier. Just load the XML into memory, e.g. via LINQ to XML. For example:

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);
    }   
}

If the content is XML, getting the result into an XML object model (whether it's XDocument, XmlDocument or XmlReader) is likely to be more valuable than having the plain text.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Do you need to check stream for null? (resharper recommendation) – Paul C Mar 18 '15 at 12:51
  • Hm, it's not clear looking at the decompiled method either, guess check it for null for safety – Paul C Mar 18 '15 at 14:33
  • 1
    @CodeBlend: And do what? If it's an expected situation, I'd want to throw an exception... which is what will happen if you pass `null` to `XDocument.Load` anyway, so there's no benefit IMO. I'm not generally a fan of checking things "just in case, even though I don't think it could ever do this". There's a time and a place for it, but if you take that approach for *every* method you end up with a horrible mess. – Jon Skeet Mar 18 '15 at 14:35
  • I agree it makes the code cumbersome but I am at a quandary where I definitely don't want to miss a null check where required but it's not always clear when a check is needed and I am not sure what logic using this case as an example that leads you to think it can't be null? I guess I am asking where to draw the line to make the code robust yet not verbose? – Paul C Mar 18 '15 at 20:19
  • 2
    @CodeBlend: Well again, what would you do if you checked and found it *was* null? In most cases you basically can't proceed, so you'd want to throw an exception saying something was unexpectedly null - and surely that's what NullReferenceException or ArgumentNullException will do for you... – Jon Skeet Mar 18 '15 at 20:59
3

This article gives a good overview of using the HttpWebResponse object:How to use HttpWebResponse

Relevant bits below:

HttpWebResponse webresponse;

webresponse = (HttpWebResponse)webrequest.GetResponse();

Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);

string Response = loResponseStream.ReadToEnd();

loResponseStream.Close();
webresponse.Close();

return Response;
budi
  • 6,351
  • 10
  • 55
  • 80
CubanX
  • 5,176
  • 2
  • 29
  • 44
  • If a web server is using Windows code page 1252 as its encoding, it's a sad day :( You should grab it from the response... which is tricky. See my answer for a workaround in this particular case. – Jon Skeet Jul 17 '10 at 21:09
  • Doh! Not my code :) It's from the article, was just trying to help out by giving him a shortcut to the relevant bits. Danger of drive by help :) – CubanX Jul 19 '10 at 13:35
2
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
budi
  • 6,351
  • 10
  • 55
  • 80
Châu Nguyễn
  • 269
  • 3
  • 5
  • The other answers already cover this way of doing it. Also, I don't think this uses the correct encoding to decode the text. – Sam Jan 12 '16 at 22:39
1

response.GetResponseStream() should be used to return the response stream. And don't forget to close the Stream and Response objects.

decyclone
  • 30,394
  • 6
  • 63
  • 80
0

If you http request is Post and request.Accept = "application/x-www-form-urlencoded"; then i think you can to get text of respone by code bellow:

var contentEncoding = response.Headers["content-encoding"];
                        if (contentEncoding != null && contentEncoding.Contains("gzip")) // cause httphandler only request gzip
                        {
                            // using gzip stream reader
                            using (var responseStreamReader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)))
                            {
                                strResponse = responseStreamReader.ReadToEnd();
                            }
                        }
                        else
                        {
                            // using ordinary stream reader
                            using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
                            {
                                strResponse = responseStreamReader.ReadToEnd();
                            }
                        }
Chung Nguyen
  • 1,011
  • 1
  • 8
  • 8