在C#中創建一個HTTP客戶端可以使用HttpClient
類。下面是一個簡單的示例代碼:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine("Request failed with status code: " + response.StatusCode);
}
}
}
}
在上面的代碼中,我們創建了一個HttpClient
對象,然后通過調用GetAsync
方法來發送一個GET請求,并且等待響應。如果響應狀態碼為成功,則打印出響應體的內容,否則打印出請求失敗的狀態碼。