0

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.

Abde
  • 31
  • 4
  • I forgot to mention that all calls from Postman always work without requiring retries. – Abde Jul 19 '23 at 16:13
  • Since it reaches the `Console.WriteLine` call, it must be failing somewhere else. Please include more context. Aslo, when you forget to mention something, use the [edit feature](https://stackoverflow.com/posts/76723283/edit) – Aluan Haddad Jul 19 '23 at 17:32
  • Thanks! Didn't know that I could edit it. About the program, that's it. I need to connect to the apiUrl but the first request returns always "RequestTimeout"... I've also tried to add `client.Timeout = TimeSpan.FromSeconds(30);` so it doesn't stop but it didn't work – Abde Jul 19 '23 at 19:57

0 Answers0