-1

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.sstatic.net/9iR3g.png

2

2 Answers 2

0

It should be easy as

var client = new HttpClient();
var results = await client.GetAsync("https://stackoverflow.com");
Console.WriteLine(results.StatusCode);
Sign up to request clarification or add additional context in comments.

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.