DownloadString返回404错误:站点需要用户代理标头

时间:2014-04-11 00:06:15

标签: c# .net http-headers

我有一个C#程序,直到一两天前工作正常。我使用以下代码段来抓取页面:

string strSiteListPath = @"http://www.ngs.noaa.gov/CORS/dates_sites.txt";
Uri uriSiteListPath = new Uri(strSiteListPath);
System.Net.WebClient oWebClient = new System.Net.WebClient();
strStationList = oWebClient.DownloadString(uriSiteListPath);

但它始终返回404 Not Found错误。该页面完全存在,欢迎您自己尝试。因为它在几天前就已经工作了,而且我的代码中没有任何内容发生变化,我可能会认为Web服务器可能会以某种方式发生变化。那很好,它会发生,但到底发生了什么?

为什么我可以手动浏览文件,但是DownloadString无法获取文件?

编辑:

为了完整性,代码现在看起来像:

string strSiteListPath = @"http://www.ngs.noaa.gov/CORS/dates_sites.txt";
Uri uriSiteListPath = new Uri(strSiteListPath);

System.Net.WebClient oWebClient = new System.Net.WebClient();
oWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0");

strStationList = oWebClient.DownloadString(uriSiteListPath);

再次感谢Thomas Levesque!

1 个答案:

答案 0 :(得分:1)

显然,该网站要求您拥有有效的User-Agent标头。如果您将该标题设置为类似的内容:

Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0

然后请求正常。