use*_*795 12 c# webclient header response
我正在尝试创建我的第一个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());
Run Code Online (Sandbox Code Playgroud)
RMa*_*tov 22
您可以像这样使用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));
Run Code Online (Sandbox Code Playgroud)
来自https://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders(v=vs.110).aspx
如果您想查看完整的答复,建议您使用WebRequest/ WebResponse代替WebClient。那是一个更底层的API- WebClient旨在使非常简单的任务(例如以字符串形式下载响应正文)变得简单。
(或者在.NET 4.5中,您可以使用HttpClient。)
这是一个如何使用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());
Run Code Online (Sandbox Code Playgroud)
另外,我真的建议您将http逻辑抽象到它自己的对象中,并传入url,UserAgent和ContentType。