Read text from response

C#asp.net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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;

Solution 5 - C#

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

Solution 6 - C#

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

Solution 7 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiraj ChoubeyView Question on Stackoverflow
Solution 1 - C#STWView Answer on Stackoverflow
Solution 2 - C#SamView Answer on Stackoverflow
Solution 3 - C#Jon SkeetView Answer on Stackoverflow
Solution 4 - C#CubanXView Answer on Stackoverflow
Solution 5 - C#Châu NguyễnView Answer on Stackoverflow
Solution 6 - C#decycloneView Answer on Stackoverflow
Solution 7 - C#Chung NguyenView Answer on Stackoverflow