在C#中的WebClient阅读响应头 [英] Read response header from WebClient in C#

查看:961
本文介绍了在C#中的WebClient阅读响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建我的第一个Windows客户端(这是我的拳头张贴她的),须以网络服务沟通,但我有一些麻烦读取响应头有回来。在我响应字符串我收到了很好的JSON文件后面(这是我的下一个问题),但我不能够看到/阅读在响应头,只有身体。

$ B $ ; b

下面是我使用的代码

  WebClient的MyClient =新的WebClient(); 
MyClient.Headers.Add(内容类型,应用/ JSON);
MyClient.Headers.Add(用户代理,DIMS /0.1 + HTTP://www.xxx.dk);
VAR urlstring =http://api.xxx.com/users/+ Username.Text;
串响应= MyClient.DownloadString(urlstring.ToString());


解决方案

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

  //获得包含从响应头名称/值对的WebHeaderCollection实例。 
WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;

Console.WriteLine(\\\
Displaying响应headers\\\
);
//循环responseHeaders和显示标题名称/值对。
表示(INT I = 0; I&下; myWebHeaderCollection.Count;我++)
Console.WriteLine(\t+ myWebHeaderCollection.GetKey(I)+=+ myWebHeaderCollection.Get(ⅰ ));



从的https://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders(v=vs.110)。 ASPX


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

解决方案

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

这篇关于在C#中的WebClient阅读响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆