L
L
LebedevStr2021-02-05 20:59:41
Parsing
LebedevStr, 2021-02-05 20:59:41

How to retry a webrequest on error (C#)?

req         = (HttpWebRequest) WebRequest.Create(get_url);
   req.Timeout = 1500;
   resp        = (HttpWebResponse) req.GetResponse();
   sr          = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("utf-8"));
   content     = sr.ReadToEnd();
   sr.Close();


How to make a forced request cycle if the response code is not 200?
Sometimes the content is NOT returned by the link (the API is overloaded) - but when the request is repeated, a valid response is returned.

Thanks

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Bannikov, 2021-02-05
@LebedevStr

1. You just repeat requests in a cycle with some periodicity
2. Instead of WebRequest, it is better to use HttpClient
3. To avoid sawing bicycles - use Polly

D
Developer, 2021-02-05
@samodum

while(True){
    try{
      здесь твои запросы
    }
    catch{
       ...
    }
}

D
Daniil Vasilyev, 2021-02-06
@hello_my_name_is_dany

Through recursion, as an option

async Task<string> SendRequestUntilSuccess(string url)
{
    try	
    {
        HttpResponseMessage response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return response.Content.ReadAsStringAsync();
    }
    catch(HttpRequestException e)
    {
        return SendRequestUntilSuccess(url);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question