Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read response header from WebClient in C#

I'm trying to create my first windows client (and this is my fist post her), there shall communicate with a "web services", but i have some trouble to read the response header there is coming back. In my response string do I received a nice JSON document back (and this is my next problem), but i'm not able to "see/read" the header in the response, only the body.

Below is the code i'm using.

        WebClient MyClient = new WebClient();
        MyClient.Headers.Add("Content-Type", "application/json");
        MyClient.Headers.Add("User-Agent", "DIMS /0.1 +http://www.xxx.dk");
        var urlstring = "http://api.xxx.com/users/" + Username.Text;
        string response = MyClient.DownloadString(urlstring.ToString());
like image 354
user3352795 Avatar asked Feb 25 '14 19:02

user3352795


Video Answer


2 Answers

You can use WebClient.ResponseHeaders like this:

// Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;

Console.WriteLine("\nDisplaying the response headers\n");
// Loop through the ResponseHeaders and display the header name/value pairs. 
for (int i=0; i < myWebHeaderCollection.Count; i++)             
    Console.WriteLine ("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));

From https://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders(v=vs.110).aspx

like image 99
RustemMazitov Avatar answered Oct 17 '22 06:10

RustemMazitov


If you want to see the full response, I suggest you use WebRequest/WebResponse instead of WebClient. That's a more low-level API - WebClient is meant to make very simple tasks (such as downloading the body of a response as a string) simple.

(Or in .NET 4.5 you could use HttpClient.)

like image 36
Jon Skeet Avatar answered Oct 17 '22 06:10

Jon Skeet