在C#中从WebClient读取响应头

时间:2014-02-25 19:28:49

标签: c# header response webclient

我正在尝试创建我的第一个Windows客户端(这是我的第一个帖子),应该与“Web服务”通信,但是我有一些麻烦来阅读回复的响应标题。在我的响应字符串中,我收到了一个不错的JSON文档(这是我的下一个问题),但是我无法“看到/读取”响应中的标题,只有正文。

以下是我正在使用的代码。

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

6 个答案:

答案 0 :(得分:20)

您可以像这样使用WebClient.ResponseHeaders:

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

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

答案 1 :(得分:5)

如果您想查看完整回复,建议您使用WebRequest / WebResponse代替WebClient。这是一个更低级别的API - WebClient旨在使非常简单的任务(例如将响应的主体作为字符串下载)变得简单。

(或者在.NET 4.5中,您可以使用HttpClient。)

答案 2 :(得分:4)

以下是如何使用WebRequest / WebResponse的示例,这是 @Jon Skeet 所讨论的内容。

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

另外,我真的建议你将http逻辑抽象出它自己的对象并传入url,UserAgent和ContentType。

答案 3 :(得分:3)

这也有效

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

答案 4 :(得分:3)

使用WebClient()的简单方法,结合上面提到的MSDN示例(MSDN示例没有明确说明如何发起请求)。不要被Properties.Settings.Default.XXXX值混淆,这些只是从App.settings文件中读取的字符串变量。我希望它有所帮助:

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

答案 5 :(得分:0)

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