我不了解變數型別以及如何利用客戶端檢索 http 狀態代碼。client 變數是一個標準的 HttpClient 物件。
附圖是我試圖檢索狀態碼的功能。任何幫助將不勝感激。[1]:https ://i.stack.imgur.com/9iR3g.png
uj5u.com熱心網友回復:
它應該很容易
var client = new HttpClient();
var results = await client.GetAsync("https://stackoverflow.com");
Console.WriteLine(results.StatusCode);
uj5u.com熱心網友回復:
你的問題是你沒有得到回應物件。您正在獲取回應正文的內容。
這是一個示例代碼:
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);
}
PostAsync 和所有其他操作也是如此......
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495275.html
