LINQ to XML 用户代理标头值
本文关键字:用户代理 to XML LINQ | 更新日期: 2023-09-27 18:37:11
如何
为 LINQ to XML 指定 HTTP 用户代理标头,以便在调用 XElement.Load(url)
时用于其请求?
我用于调用 Web API,并且我的客户端需要在用户代理标头中正确描述自身。
您可以使用WebClient指定用户代理
using (var webClient = new WebClient())
{
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
using (var stream = webClient.OpenRead("http://server.com"))
{
XElement.Load(stream);
}
}
或
using (var webClient = new WebClient())
{
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
XElement.Parse(webClient.DownloadString(url));
}