-1

I am working on .net core 3.1. I am trying to use https://services.timeanddate.com/ API.

when debuggeing I got IsCancellationRequested = true and go to exception. The request that was canceled that line below: using var response = await _client.GetAsync(url);

service

  public class HolidayService : IHolidayService
    {
        private readonly HttpClient _client;
        private readonly IHttpClientFactory _clientFactory;

         static string httpaddr = "https://api.xmltime.com";  // I need this url result in post man "https://api.xmltime.com/holidays?accesskey=dYjG8ztthf&secretkey=veUV06dNmrnp7bbaYq0u&version=3&country=ro&year=2021"
      //  static string httpaddr = "https://date.nager.at";   // for this I can get result in postman "https://date.nager.at/api/v3/publicholidays/2020/US"

        static HttpClient Http = new HttpClient() { BaseAddress = new Uri(httpaddr) };


        public HolidayService(HttpClient client)
        {
            _client = client;
            _client.Timeout = TimeSpan.FromMilliseconds(30);
        }
        public HolidayService(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }

        public async Task<List<Holiday>> GetHolidays(string country, int year)
        {
            string url = string.Format($"/holidays?accesskey=dYjG8ztthf&secretkey=veUV06dNmrnp7bbaYq0u&version=3&country=ro&year=2021&lang=en");
           // for url i get IsCancellationRequested = true and go to TaskCanceledException exception . How to solve?
           
            // string url2 = string.Format($"/api/v2/PublicHolidays/2020/US"); // for this ulr2 there is no exception

            var result = new List<Holiday>();
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken token = source.Token;
                var response = await Http.GetAsync(url, token);

                if (response.IsSuccessStatusCode)
                {
                    using var responseStream = await response.Content.ReadAsStreamAsync();
                    result = await JsonSerializer.DeserializeAsync<List<Holiday>>(responseStream);
                }
                else
                {
                    throw new HttpRequestException(response.ReasonPhrase);
                }
                // var response = await _client.GetAsync(url, token);
                // using var response = await _client.GetAsync(url);
            }
            // Filter by InnerException.
            catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
            {
                // Handle timeout.
                Console.WriteLine("Timed out: " + ex.Message);
            }
            catch (TaskCanceledException ex)
            {
                // Handle cancellation.
                Console.WriteLine("Canceled: " + ex.Message);  // this is my exception
            }

            return result;


        }

I want to know why this cancelation exception is occurs? For this https://date.nager.at my code is working fine and got json results as excepted. But Why https://services.timeanddate.com/ API give exception and request was canceled that line below: using var response = await _client.GetAsync(url);

Why i could not get excepted result from this https://services.timeanddate.com/ API.

JSON result is for https://services.timeanddate.com/ API.:

{
    "urlid": null,
    "url": null,
    "country": null,
    "name": null,
    "oneliner": null,
    "date": null,
    "types": null,
    "uid": null
}

How to get all response from this https://services.timeanddate.com/ API?

hanu
  • 53
  • 1
  • 10
  • response contains nulls because `var result = new Holiday();` and it never changes because exception. Exception says that there is problem with getting response from server. Could you provide `_client` configuration? – Leszek Mazur Sep 18 '21 at 06:19
  • yes. Also I use another API which is `https://date.nager.at` It works fine. But when is use `https://services.timeanddate.com/` this I got exception. What is the issue? – hanu Sep 18 '21 at 07:21
  • What is `_client`? – Rowan Smith Sep 18 '21 at 07:41
  • @RowanSmith `static string httpaddr = "https://api.xmltime.com"; static HttpClient _client = new HttpClient() { BaseAddress = new Uri(httpaddr) };` – hanu Sep 18 '21 at 07:42
  • @hanu please clarify your question. Written this way it is impossible to help you. In the first part of the question you talk about cancellation and timeouts. In the secondo part of your question it seems that you are actually able to get a response from the API (so, no timeout occurs), but the shape of the response itself it's not the one you would expect. – Enrico Massone Sep 18 '21 at 08:00
  • Your request is failing due to timeout. HttpClient.GetAsync() is throwing a TaskCancelledException due to a time out connecting. You need to focus on why the HttpClientis failing to connect to the server. – Rowan Smith Sep 18 '21 at 08:00
  • @hanu so please, clarify what you are trying to understand and focus this question on one problem only. Are you struggling with timeouts ? Are you trying to understand how to cancel an HTTP request ? Are you getting an unexpected response from an API you are calling ? Write down a clearer question and please, if possible, focus on one problem only. If you have more than one problem, open different questions (one per problem) and tag them properly. – Enrico Massone Sep 18 '21 at 08:02
  • @hanu remember also to specify the version of .NEt or .NET core you are using, because the HttpClient communicates the timeout of the called server in different ways, based on the actual runtime framework. See here in the remarks block https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getasync?view=net-5.0#System_Net_Http_HttpClient_GetAsync_System_String_ – Enrico Massone Sep 18 '21 at 08:05
  • @RowanSmith I have updated the question. Now do you get my issue – hanu Sep 18 '21 at 08:28

1 Answers1

0

I have tried a subset of your code, as follows and it is working absolutely fine.

public static async Task<byte[]> TestUrl()
{
    HttpClient http = new() { BaseAddress = new Uri("https://api.xmltime.com") };
    CancellationTokenSource cts = new();

    var response = await http.GetAsync("/holidays?accesskey=dYjG8ztthf&secretkey=veUV06dNmrnp7bbaYq0u&version=3&country=ro&year=2021&lang=en",cts.Token);

    if(response.IsSuccessStatusCode)
        return await response.Content.ReadAsByteArrayAsync();
    else
        throw new HttpRequestException(response.ReasonPhrase);
}

This function returns a byte[] containing the JSON. If this function doesn't work for you then that implies that you might have a networking problem.

Rowan Smith
  • 1,815
  • 15
  • 29
  • I got `System.Threading.Tasks.TaskCanceledException: The operation was canceled. at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)` – hanu Sep 18 '21 at 10:00
  • Then you have a networking problem. Your computer is unable to connect to the URI it isn't anything to do with your code. Copy the full URL and put it into a web browser to check what's happening or try it in `curl`. You'll need to troubleshoot your network connectivity. – Rowan Smith Sep 18 '21 at 10:36
  • The url works fine in browser. – hanu Sep 18 '21 at 12:48