【问题标题】:webclient headers classwebclient 头文件类
【发布时间】:2010-06-30 23:45:14
【问题描述】:

我正在使用带有 cookie 的 WebClient 类,如下所述:Using CookieContainer with WebClient class

向此 WebClient 发出的每个请求添加自定义用户代理需要哪些步骤?

我试着把

Headers.Add(HttpRequestHeader.UserAgent, "...") 

插入

protected override WebRequest GetWebRequest

但这不起作用:“必须使用适当的属性修改此标头”。

【问题讨论】:

  • 您知道 WebClient 是 .NET 的一部分,而不是 C# 的一部分吗?

标签: .net webclient


【解决方案1】:

来自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 ();
        }
    }

【讨论】:

  • 您知道您的代码未格式化吗?下次,请在编辑器中选择它,然后按 Control-K。
  • 旧答案,但它很快解决了我的问题,因此值得一票。
【解决方案2】:

答案有点晚,但它就在这里;我和你有同样的问题,并通过在你链接的示例中添加一行来解决它:

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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多