I need to download an xml from an https url, so I tried to access the url with the HttpClient like this:
string apiUrl = "https://my-url.com/my_data.xml";
string username = "user";
string password = "pass";
var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = authValue;
var content = await client.GetAsync(apiUrl);
Console.WriteLine("Content status: " + content.StatusCode);
}
The problem is that every time I execute the program, it prints "Content status: RequestTimeout". But when I add more calls or a loop, for example:
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = authValue;
for(int i = 0; i < 3; i++)
{
var content = await client.GetAsync(apiUrl);
Console.WriteLine("Content status: " + content.StatusCode);
}
}
It prints:
Content status: RequestTimeout
Content status: OK
Content status: OK
It doesn't matter how many times I execute it or the number of iterations in the loop, the first one is always "Error 408, Request Timeout".
All calls through Postman or directly using a web browser, consistently succeed without requiring retries.
Any idea why it doesn't work the first in my program?
If I can't solve the problem, I will do the request two times and that's it, but I would like to have a clean code without quick fixes.