我正在使用带有cookie的WebClient类,如下所述:Using CookieContainer with WebClient class
将自定义用户代理添加到此WebClient发出的每个请求中需要执行哪些步骤?
我试着把
Headers.Add(HttpRequestHeader.UserAgent, "...")
进入
protected override WebRequest GetWebRequest
但这不起作用:“必须使用适当的属性修改此标头”。
答案 0 :(得分:3)
来自http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx,
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main (string[] args)
{
if (args == null || args.Length == 0)
{
throw new ApplicationException ("Specify the URI of the resource to retrieve.");
}
WebClient client = new WebClient ();
// Add a user agent header in case the
// requested URI contains a query.
client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead (args[0]);
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();
}
}
答案 1 :(得分:0)
有点迟到的答案,但在这里;我遇到了和你一样的问题,并通过在你链接的例子中添加一行来解决它:
public class CookieAwareWebClient : WebClient
{
private CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).UserAgent = "CUSTOM USERAGENT HERE";
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}