在现代软件开发中,与Web API进行通信是必不可少的技能。C# 提供了 HttpClient 类,用于轻松发送 HTTP 请求并接收响应。本教程将手把手教你如何使用 C# 的 HttpClient 发送 GET 和 POST 请求,即使你是编程小白也能快速上手!

HttpClient 是 .NET 中用于发送 HTTP 请求和接收 HTTP 响应的类。它支持异步操作,性能优秀,并且可以复用,非常适合在应用程序中频繁调用 Web API。
确保你已安装 .NET SDK(建议使用 .NET 6 或更高版本),并创建一个控制台应用程序:
dotnet new console -n HttpDemocd HttpDemo
GET 请求用于从服务器获取数据。下面是一个完整的 C# 示例,演示如何使用 HttpClient 发送 GET 请求并读取响应内容。
using System;using System.Net.Http;using System.Threading.Tasks;class Program{ static async Task Main(string[] args) { // 创建 HttpClient 实例(推荐使用 using 声明) using var client = new HttpClient(); try { // 发送 GET 请求 HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1"); // 确保请求成功 response.EnsureSuccessStatusCode(); // 读取响应内容为字符串 string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"请求出错: {e.Message}"); } }}这段代码会向 https://jsonplaceholder.typicode.com/posts/1 发起 GET 请求,并打印返回的 JSON 数据。这是学习 C# HttpClient 和 C#发送GET请求 的经典示例。
POST 请求通常用于向服务器提交数据(如表单、JSON 等)。下面演示如何发送包含 JSON 数据的 POST 请求。
using System;using System.Net.Http;using System.Text;using System.Text.Json;using System.Threading.Tasks;class Program{ static async Task Main(string[] args) { using var client = new HttpClient(); // 准备要发送的数据 var postData = new { title = "Hello from C#", body = "This is a POST request example.", userId = 1 }; // 将对象序列化为 JSON 字符串 string json = JsonSerializer.Serialize(postData); var content = new StringContent(json, Encoding.UTF8, "application/json"); try { // 发送 POST 请求 HttpResponseMessage response = await client.PostAsync( "https://jsonplaceholder.typicode.com/posts", content); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"请求出错: {e.Message}"); } }}这个例子展示了如何构造 JSON 数据并通过 HttpClient 发送 POST 请求。这是实现 C#发送POST请求 的标准做法。
HttpClient 实例,应复用或使用 IHttpClientFactory(在 ASP.NET Core 中)。async/await 进行异步调用,避免阻塞主线程。通过本 HTTP请求教程,你已经学会了如何在 C# 中使用 HttpClient 发送 GET 和 POST 请求。无论你是构建桌面应用、Web 后端还是微服务,这些技能都非常实用。
记住:掌握 C# HttpClient 是迈向专业 C# 开发者的重要一步。多练习、多尝试,你很快就能熟练运用!
本文由主机测评网于2025-12-23发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/20251212032.html