如何在 WebClient 中设置 User-Agent [英] How to set User-Agent in WebClient

查看:72
本文介绍了如何在 WebClient 中设置 User-Agent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I used the code below to open a stream request to a youtube video, but it always return an exception "The remote server returned an error: NotFound". Then I tried to use Fiddler to detect the problem, and I saw that the WebClient auto set User-Agent field to NativeHost, not my User-Agent as below.

我向 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

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

Please give me some advice. Many thanks

推荐答案

您可以使用此代码

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

这篇关于如何在 WebClient 中设置 User-Agent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆