使用WebClient并接收错误403

时间:2014-08-14 14:39:29

标签: c# webclient

我目前正在使用WebClient打开几个网站,但一段时间后我开始收到Error 403条消息。
我假设是因为我经常/快速地击中他们的服务器。我假设我需要做的就是在请求之间添加Thread.Sleep时间范围。

由于我必须多次这样做,是否有关于如何处理节流问题的建议而不必花费大量时间?
例如,请求之间的3秒最终会让我像3小时一样。

所以问题是,Thread.Sleep真的是正确的解决方案吗?如果是的话,它的时间框架是什么时候?

作为附注,我还使用了HttpWebRequest并遇到了同样的问题。我仍然在其他代码项目中使用它,并且在技术上我希望利用HttpWebRequest

为这些其他代码项目使用相同的解决方案(或接近它)

1 个答案:

答案 0 :(得分:0)

尝试并行运行请求

public static void RunRequest(Uri uri, Action<string> onCompleted)  
{
    var client = new WebClient();
    client.DownloadStringCompleted += (sender, e) => onCompleted(e.Result);
    client.DownloadStringAsync(uri);
};

警告:代码不是testet,我从未使用WebClient

private const int _maxParallelRequest = 10;
private int _requestCount = 0;
private readonly object _sync = new object();
private ManualResetEvent _ev = new ManualResetEvent(false);

while(true)
{
    foreach (var uri in _allYourUris)
    {
        var wait = false;
        lock (_sync)
        {
            if (_requestCount >= _maxParallelRequest)
                wait = true;
        }

        if (!wait)
        {
            lock (_sync) { ++_requestCount; }
            RunRequest(uri, r => {
                lock (_sync) 
                { 
                    --_requestCount; 
                    _ev.Set();
                }    
                // handle r
            });
            continue;
        }
        _ev.WaitOne();
    }
    Thread.Sleep(3000);
}
相关问题