Reputation: 185
I've been using the WebClient in C# to get specific data from a webpage. That works well until I do it more than 2 times. If I do it more than more than 2 times it gives me the "(429) Too Many Requests." error. I have looked at other questions regarding this issue, by the way.
Upvotes: 6
Views: 27902
Reputation: 107
This post is old, but I had the same issue downloading images from my webserver. I found the solution on this post
// THIS LINE IS THE IMPORTANT ONE
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
"Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
"InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";
I haven't had any issues since.
Upvotes: 0
Reputation: 11
I know that this thread is quite old. but I wanted to share solutions
Maybe you can try polly as interceptor to retry the request.
for the policy handler
serviceCollection.AddHttpClient<IExternalAPI, ExternalAPI>(client =>
{
var url= "";
url = config.GetSection("Config").GetValue<string>("baseUrl");
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}).AddPolicyHandler((provider, request) =>
{
return Policy.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests)
.RetryAsync(1, async (response, retryCount, context) =>
{
if (response.Result.StatusCode == HttpStatusCode.Unauthorized)
{
// Add delay here
Thread.Sleep(1000);
Logger.LogInformation("Unauthorized Request Occured, Re-authenticating");
await client.Authenticate();
}
// refresh auth token.
Upvotes: 1
Reputation: 344
I recomend to use this code. it's not freezes GUI (wait for 15 seconds):
DateTime Tthen = DateTime.Now;
do
{
//Your code or nothing...
Application.DoEvents();
}
while (Tthen.AddSeconds(15) > DateTime.Now);
Upvotes: -1
Reputation: 1003
It is not a C# problem. It is response from the web server. Probably some kind of anti-DOS filter. Try to make a pause between requests i.e. System.Threading.Thread.Sleep(5000);
before each requests.
Upvotes: 11