在C#中,你可以使用HttpClient類來發送HTTP請求并獲取響應內容。以下是一個簡單的示例,展示了如何使用HttpClient獲取HTTP響應內容:
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace HttpClientExample
{
class Program
{
static async Task Main(string[] args)
{
// 創建一個HttpClient實例
using (HttpClient httpClient = new HttpClient())
{
try
{
// 發送GET請求到指定的URL
HttpResponseMessage response = await httpClient.GetAsync("https://api.example.com/data");
// 確保請求成功
response.EnsureSuccessStatusCode();
// 獲取響應內容
string responseBody = await response.Content.ReadAsStringAsync();
// 輸出響應內容
Console.WriteLine("Response content:");
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
}
}
}
在這個示例中,我們首先創建了一個HttpClient實例,然后使用GetAsync方法發送一個GET請求到指定的URL。我們使用EnsureSuccessStatusCode方法確保請求成功,然后使用Content.ReadAsStringAsync方法獲取響應內容。最后,我們將響應內容輸出到控制臺。