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());
Here is an example of how to use WebRequest/WebResponse, which is what @Jon Skeet was talking about.
Also I really recommend you abstract the http logic out to it's own object and pass in url, UserAgent and ContentType.
You can use WebClient.ResponseHeaders like this:
From https://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders(v=vs.110).aspx
If you want to see the full response, I suggest you use
WebRequest
/WebResponse
instead ofWebClient
. 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
.)The below code is very similar to the MSDN documentation but I use
Headers
instead of theResponseHeaders
and didn't receive the null reference exception that I received when running the MSDN code. https://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders(v=vs.110).aspxThis also works too
A simple way using WebClient(), combined with the MSDN example as mentioned above (the MSDN example does not explicitly explain how to initiate the request). Don't be confused by the
Properties.Settings.Default.XXXX
values, these are just string variables read from the App.settings file. I hope it helps: