首页 > 解决方案 > 如何正确添加 WebRequest 标头?

问题描述

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

我昨天写了这个,它工作得很好。今天突然这不再起作用了。使用 System.Net.WebRequest 时无法设置一些 HTTP 标头有一个几乎完全相同的问题,但答案https://stackoverflow.com/a/4752359/4427870说我不能使用User-Agent标头,但我确实在前一天使用过。

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

我想使用WebRequest而不是WebClientor HttpWebRequest

标签: c#.netwebrequest

解决方案


您需要UserAgent直接设置,使用CreateHttpwhich returns 代替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是一个受限制的标头,必须通过属性设置,这里有一个所有受限制标头的列表


推荐阅读