问题
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());
回答1:
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
回答2:
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.)
回答3:
Here is an example of how to use WebRequest/WebResponse, which is what @Jon Skeet was talking about.
var urlstring = "http://api.xxx.com/users/" + Username.Text;
var MyClient = WebRequest.Create(urlstring) as HttpWebRequest;
//Assuming your using http get. If not, you'll have to do a bit more work.
MyClient.Method = WebRequestMethods.Http.Get;
MyClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
MyClient.Headers.Add(HttpRequestHeader.UserAgent, "DIMS /0.1 +http://www.xxx.dk");
var response = MyClient.GetResponse() as HttpWebResponse;
for (int i = 0; i < response.Headers.Count; i++ )
Console.WriteLine(response.Headers.GetKey(i) + " -- " + response.Headers.Get(i).ToString());
Also I really recommend you abstract the http logic out to it's own object and pass in url, UserAgent and ContentType.
回答4:
This also works too
string acceptEncoding = client.ResponseHeaders["Accept"].ToString();
回答5:
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:
using (var client = new WebClient()){
try{
var webAddr = Properties.Settings.Default.ServerEndpoint;
Console.WriteLine("Sending to WebService " + webAddr);
//This only applies if the URL access is secured with HTTP authentication
if (Properties.Settings.Default.SecuredBy401Challenge)
client.Credentials = new NetworkCredential(Properties.Settings.Default.UserFor401Challenge, Properties.Settings.Default.PasswordFor401Challenge);
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.OpenRead(webAddr);
// Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
WebHeaderCollection myWebHeaderCollection = client.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));
}
catch (Exception exc){
Console.WriteLine( exc.Message);
}
}
回答6:
The below code is very similar to the MSDN documentation but I use Headers
instead of the ResponseHeaders
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).aspx
WebClient MyClient = new WebClient();
MyClient.Headers.Add("Content-Type", "application/json");
MyClient.Headers.Add("User-Agent", "DIMS /0.1 +http://www.xxx.dk");
WebHeaderCollection myWebHeaderCollection = MyClient.Headers;
for (int i = 0; i < myWebHeaderCollection.Count; i++)
{
Console.WriteLine("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));
}
来源:https://stackoverflow.com/questions/22024233/read-response-header-from-webclient-in-c-sharp