简体   繁体   中英

Sending a POST request with retry using HTTPClient

So I've been searching like a mad man after a way to solve this issue, but I can't seem to find an answer.

So, I need to send a POST request with HTTPClient in C# to a server, and if the server isn't running it will keep sending the request until it connects (or dies after a nr of attempts). But I always get the exception System.Net.Http.HttpRequestException , which wouldn't be a problem if I just could store it (or something) and try again.

I found a couple of ways that people tried to do this, and I've tried them all. Creating a for-loop that loops and catches the exception that the program throws, adds to the counter and tries again. Creating a while-loop that loops until the HttpResponseMessage.IsSuccessStatusCode == true . I've even gone to such lengts as restarting the program if it can't connect (yeah, I'm that desperate).

So, I had to see if anyone of you guys might have a solution to this problem, or if you maybe had a better way to solve this problem. Here is the code im running, thanks for your help! EDIT: Just to add some clarity, the exception is thrown at the "rep"-variable, and the code never runs further than to that variable. And I've tried to make the HTTPResponseMessage variable just a "var" and await the Postasync method to.

HttpResponseMessage rep = new HttpResponseMessage();

try
{
    rep = client.PostAsync("https://localhost:9999/", content).Result;
}
catch (Exception e)
{

}


Task t1 = Task.Factory.StartNew(() => ContinueTrasmission(client, c1.name, c1.state));

You have to look for retry libraries, for example Polly

var policy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetry(_retryCount, retryAttempt => 
        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

policy.Execute(() => DoSomething());

A solution could be:

bool success = false;

while (!success)
{
    var rep = new HttpResponseMessage();

    try
    {
        rep = client.PostAsync("https://localhost:9999/", content).Result;

        //No exception here. Check your condition and set success = true if satisfied.
    }
    catch (Exception e)
    {
        //Log your exception if needed
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM