Home > Blockchain >  How do I return the HTTP status code when I'm making a JSON post in C#?
How do I return the HTTP status code when I'm making a JSON post in C#?

Time:06-15

I don't understand the variable types and how i can utilize client to retrieve the http Status code. The client variable is a standard HttpClient object.

The attached picture is the function I'm trying to retrieve the status code during. Any help would be greatly appreciated. [1]: https://i.stack.imgur.com/9iR3g.png

CodePudding user response:

It should be easy as

var client = new HttpClient();
var results = await client.GetAsync("https://stackoverflow.com");
Console.WriteLine(results.StatusCode);

CodePudding user response:

Your issue is that you're not getting response object. You are getting the content of the body of the response.

Here is a sample code:

void SimpleApiCall()
{ 
    Uri endpoint = new Uri("https://www.7timer.info/bin/");

    using var client = new HttpClient();
    client.BaseAddress = endpoint;

    // Get the response only here, and then get the content
    // I'm using GetAwaiter().GetResult() because client.GetAsync() returns a Task and you're not using the async await since this is a button click event
    var response = client.GetAsync("astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0").GetAwaiter().GetResult();

    // Status code will be available in the response
    Console.WriteLine($"Status code: {response.StatusCode}");

    // For the Reason phrase, it will be Ok for 200, Not Found for a 404 response...
    Console.WriteLine($"Reason Phrase: {response.ReasonPhrase}");

    // read the content of the response without the await keyword, use the .GetAwaiter().GetResult()
    var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
    Console.WriteLine("Content:");
    Console.WriteLine(content);
}

Same goes for PostAsync and all the other operations...

  • Related