在C#中創(chuàng)建一個(gè)HTTP客戶端可以使用HttpClient
類。下面是一個(gè)簡(jiǎn)單的示例代碼:
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);
}
}
}
}
在上面的代碼中,我們創(chuàng)建了一個(gè)HttpClient
對(duì)象,然后通過(guò)調(diào)用GetAsync
方法來(lái)發(fā)送一個(gè)GET請(qǐng)求,并且等待響應(yīng)。如果響應(yīng)狀態(tài)碼為成功,則打印出響應(yīng)體的內(nèi)容,否則打印出請(qǐng)求失敗的狀態(tài)碼。