如何在 WebClient 中设置 User-Agent

kie*_*t90 1 c# user-agent webclient

我使用下面的代码打开对 youtube 视频的流请求,但它总是返回异常“远程服务器返回错误:NotFound”。然后我尝试使用 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;
}
Run Code Online (Sandbox Code Playgroud)

从 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
Run Code Online (Sandbox Code Playgroud)

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

Shy*_*hah 5

您可以使用此代码

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)";
      }
Run Code Online (Sandbox Code Playgroud)