c# - 远程服务器 (403) 使用 WebClient 时出现禁止错误

标签 c# webclient

我正在尝试使用 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/

相关文章:

c# - C++ 中的数组<T ^> ^T 是什么?如何从数组中提取值?

c# - 升级到 3.9 版后无法启动 Selenium IE 驱动程序

c# - 当行具有空值时, Entity Framework 返回空对象

c# - 有没有办法让 XAML/C# StringFormat 显示较大金额的整美元,但较小金额的美分?

c# - 从网址下载后播放声音文件

c# - 使用 C# 代码下载的 zip 文件无效

C# WebClient 禁用缓存

c# - 将 C# 字符串作为 SELECT WHERE IN 的 SQL 参数传递

c# - 使用 WebClient 下载显示进度

c# - 如何 'await' WebClient.UploadStringAsync 请求?