繁体   English   中英

在C#中从WebClient读取响应头

[英]Read response header from WebClient in C#

我正在尝试创建我的第一个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());

您可以像这样使用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

如果你想看到完整的响应,我建议你使用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());

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

这也有效

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

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

下面的代码与MSDN文档非常相似,但我使用Headers而不是ResponseHeaders并且没有收到运行MSDN代码时收到的空引用异常。 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));
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM