简体   繁体   English

如何正确添加WebRequest标头?

[英]How to correctly add WebRequest header?

var webRequest = WebRequest.Create("https://vtopbeta.vit.ac.in/vtop/");
webRequest.Method = "GET";
webRequest.Timeout = 12000;
webRequest.Headers.Add("User-Agent",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
string jsonResponse;
using (var s = webRequest.GetResponse().GetResponseStream())
{
    using (var sr = new StreamReader(s ?? throw new InvalidOperationException()))
    {
        jsonResponse = sr.ReadToEnd();
    }
}

I wrote this yesterday and it worked just fine. 我昨天写了这个,它工作得很好。 Today suddenly this is not working anymore. 今天突然间这已不再适用了。 There is an almost exact question Cannot set some HTTP headers when using System.Net.WebRequest but the answer https://stackoverflow.com/a/4752359/4427870 says I cant use User-Agent header but I literally used it a day before. 有一个几乎确切的问题在使用System.Net.WebRequest时无法设置一些HTTP标头,但答案https://stackoverflow.com/a/4752359/4427870说我不能使用User-Agent标头,但我确实在前一天使用它。

The error I get: System.ArgumentException: 'The 'User-Agent' header must be modified using the appropriate property or method. Parameter name: name' 我得到的错误: System.ArgumentException: 'The 'User-Agent' header must be modified using the appropriate property or method. Parameter name: name' System.ArgumentException: 'The 'User-Agent' header must be modified using the appropriate property or method. Parameter name: name'

I'd like to use WebRequest and not WebClient or HttpWebRequest . 我想使用WebRequest而不是WebClientHttpWebRequest

You need to set UserAgent directly, use CreateHttp instead which returns HttpWebRequest , then you can do: 您需要直接设置UserAgent ,使用CreateHttp而不是返回HttpWebRequest ,然后您可以执行以下操作:

webRequest.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36";

UserAgent is a restricted header and must be set via a property, there is a list of all restricted headers here . UserAgent是一个禁区头球,必须通过属性设置,还有所有受限标题列表在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM