gpt4 book ai didi

c# - 如何在 WebClient 中设置 User-Agent

转载 作者:太空宇宙 更新时间:2023-11-03 20:07:05 25 4
gpt4 key购买 nike

我使用下面的代码打开了对 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;
}

从 Fiddler 捕获的 header :

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

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

最佳答案

您可以使用此代码

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

关于c# - 如何在 WebClient 中设置 User-Agent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22656049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com