我正在尝试使用 WebClient
查询一些 URL。
我有一个循环获取 QueryString
值的集合,并构建最终 URL,然后将其传递给客户端。
它第一次执行得很好,我得到了正确的响应,但是,当它第二次进入循环时,我得到了错误:
System.Net.WebException --> The remote server returned an error: (403) Forbidden.
如果我第一次得到回应。然后我也应该得到其余的收藏品。
有什么线索吗?我可能会错过什么?
下面是我正在使用的代码片段。
using(System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\sample.text")) {
foreach(var f in fileCollections) {
strFinalURL = string.Empty;
strFinalURL = "someURL" + f; // f can be considered as querystring param value
try {
using(var client = new WebClient()) {
test = client.DownloadString(strFinalURL);
if (!test.Contains("somecondition")) {
file.WriteLine("");
}
}
} catch (System.Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
最佳答案
一些网络服务器可以根据它们提供的用户代理字符串来阻止请求。在您的情况下,您发送一个空字符串作为用户代理。尝试添加浏览器的用户代理,任何浏览器都可以。
例如:
client.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
要获取用户代理列表,您可以单击 here .
关于c# - 远程服务器 (403) 使用 WebClient 时出现禁止错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19715970/