Read response header from WebClient in C#

不问归期 提交于 2019-12-03 05:54:09

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

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.)

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.

This also works too

string acceptEncoding = client.ResponseHeaders["Accept"].ToString();
fRENCHfRIES64

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

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));
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!