简体   繁体   English

HTTPWebRequest 403 Forbidden - 伪造网页浏览器

[英]HTTPWebRequest 403 Forbidden - faking web browser

Here is my code faking a browser request: 这是我伪造浏览器请求的代码:

HttpWebRequest webReq = WebRequest.CreateHttp(url);
webReq.CookieContainer = new CookieContainer();
webReq.Method = "GET";
webReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0";
webReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webReq.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us,en;q=0.5");
webReq.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");

webReq.AllowAutoRedirect = true;
webReq.MaximumAutomaticRedirections = 50;

using (WebResponse response = webReq.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(stream);
        return reader.ReadToEnd();
    }
}

But I get a 403 HTTP error with this URL: http://www.alchourouk.com/xml_top_article/rss.xml 但是我通过此URL收到403 HTTP错误: http//www.alchourouk.com/xml_top_article/rss.xml

I don't understand why, there is no authentication, no cookies used... 我不明白为什么,没有身份验证,没有使用cookie ...

In Postman, I have no error, and here is the code it generates: 在Postman中,我没有错误,这是它生成的代码:

var client = new RestClient("http://www.alchourouk.com/xml_top_article/rss.xml");
var request = new RestRequest(Method.GET);
request.AddHeader("postman-token", "1b40ceba-6311-0fe2-1566-62a2d59950a0");
request.AddHeader("cache-control", "no-cache");
IRestResponse response = client.Execute(request);

Nothing special here. 这里没什么特别的。 Any idea why my code gets a 403 error? 知道为什么我的代码会出现403错误吗?

What you need is the Referer HTTP header: 你需要的是Referer HTTP头:

webReq.Referer = "http://www.alchourouk.com/";

And it'll work just fine. 它会工作得很好。

Live demo here 现场演示

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

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