饼干。这是因为饼干。
当我开始深入研究这个问题时,我注意到第一次在新浏览器中打开该网站时出现了 404,但刷新后(有时一次,有时几次)该网站继续工作。
就在那时,我淘汰了 Chrome 的隐身模式和开发者工具。
网络上并没有什么太可疑的地方:如果你加载了 http,就会有一个简单的重定向到 https 版本。
但我确实注意到cookies发生了变化。这是我第一次加载页面时看到的内容:
这是一次(或几次)刷新后的页面:
注意到如何添加更多 cookie 条目了吗?该网站一定是试图阅读这些内容,但没有找到它们,然后“阻止”您。我不确定这可能是机器人预防设备或错误的编程。
不管怎样,这里是如何让你的代码工作的。此示例使用 HttpWebRequest/Response,而不是 WebClient。
string url = "https://support.microsoft.com/api/content/kb/3068708";
//this holds all the cookies we need to add
//notice the values match the ones in the screenshot above
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(new Cookie("SMCsiteDir", "ltr", "/", ".support.microsoft.com"));
cookieJar.Add(new Cookie("SMCsiteLang", "en-US", "/", ".support.microsoft.com"));
cookieJar.Add(new Cookie("smc_f", "upr", "/", ".support.microsoft.com"));
cookieJar.Add(new Cookie("smcexpsessionticket", "100", "/", ".microsoft.com"));
cookieJar.Add(new Cookie("smcexpticket", "100", "/", ".microsoft.com"));
cookieJar.Add(new Cookie("smcflighting", "wwp", "/", ".microsoft.com"));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//attach the cookie container
request.CookieContainer = cookieJar;
//and now go to the internet, fetching back the contents
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using(StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string site = sr.ReadToEnd();
}
如果您删除request.CookieContainer = cookieJar;
,它将失败并显示 404,这会重现您的问题。
代码示例的大部分跑腿工作来自这个帖子 https://stackoverflow.com/a/15207262/1043380 and 这个帖子 https://stackoverflow.com/a/14551410/1043380.