【问题标题】:How to set User-Agent in WebClient如何在 WebClient 中设置 User-Agent
【发布时间】:2014-03-26 09:08:32
【问题描述】:

我使用下面的代码打开了对 youtube 视频的流请求,但它总是返回异常“远程服务器返回错误:未找到”。然后我尝试使用 Fiddler 来检测问题,我看到 WebClient 自动将 User-Agent 字段设置为 NativeHost,而不是我的 User-Agent,如下所示。

我向 youtube 发送请求的代码:

private static Task<string> HttpGet(string uri)
{
    var task = new TaskCompletionSource<string>();

    var web = new WebClient();
    web.OpenReadCompleted += (sender, args) =>
    {
        if (args.Cancelled)
            task.SetCanceled();
        else if (args.Error != null)
            task.SetException(args.Error);
        else
        {
            //var bytes = args.Result.ReadToEnd();
            byte[] bytes = new byte[] { };
            using (MemoryStream memoryStream = new MemoryStream())
            {
                args.Result.CopyTo(memoryStream);
                bytes = memoryStream.ToArray();

                task.SetResult(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
            }
        }
    };

    web.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
    web.OpenReadAsync(new Uri(uri));

    return task.Task;
}

从 Fiddler 捕获的标头:

CONNECT www.youtube.com:443 HTTP/1.0
User-Agent: NativeHost
Host: www.youtube.com:443
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

请给我一些建议。非常感谢

【问题讨论】:

    标签: c# webclient user-agent


    【解决方案1】:

    你可以使用这个代码

    using (WebClient web = new WebClient())
        {
        web.Headers["User-Agent"] =
        "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
        "(compatible; MSIE 6.0; Windows NT 5.1; " +
        ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
          }
    

    【讨论】:

      【解决方案2】:

      试试这个添加用户代理

      web.Headers.Add("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
      

      【讨论】:

        【解决方案3】:

        你也可以这样做。

        using (WebClient webClient = new WebClient())
        {
              webClient.Headers.Add("user-agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36");
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-31
          • 2010-11-26
          相关资源
          最近更新 更多