Home > Enterprise >  How to Request JSON file with `Accept: application/json` From Check-Host.Net api in C#
How to Request JSON file with `Accept: application/json` From Check-Host.Net api in C#

Time:06-23

Im trying to get json file response like this:

{
  "ok":             1,
  "request_id":     "807dab",
  "permanent_link": "https://check-host.net/check-report/807dab",
  "nodes": {
    "us1.node.check-host.net": ["us", "USA", "Los Angeles", "5.253.30.82", "AS18978"],
    "ch1.node.check-host.net": ["ch", "Switzerland", "Zurich", "179.43.148.195", "AS50837"]
  }
}

with this code:

Uri uri = new Uri("https://check-host.net/check-tcp?host=https://sheypoor.com&max_nodes=1&node=us1.node.check-host.net");
HttpClient client = new HttpClient();
string result = client.GetStringAsync(uri).Result;
Root root = JsonConvert.DeserializeObject<Root>(result);
Console.WriteLine(root.nodes.Us1NodeCheckHostNet[0]);

but it didn't work! can somebody show me true way?

CodePudding user response:

I found my result, i had to add header to httpclinet request:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
string result = client.GetStringAsync(uri).Result;

and then it works!

CodePudding user response:

here is how I do it:

I write i method for getting a HTTPClient with de accepted header and the base uri.

        protected virtual Task<HttpClient> GetHttpClientAsync()
        {
            var client = _httpClientFactory.CreateClient();
            client.BaseAddress = new Uri(_settings.BaseUri);
            client.DefaultRequestHeaders.Add("Accept", MediaTypeNames.Application.Json);
            client.Timeout = TimeSpan.FromSeconds(10);
            return Task.FromResult(client);
        }

After you have initialized your client you can send your request as followed:

        using var client = await GetHttpClientAsync();
        using var response = await client.GetAsync(path);
  • Related