如何在C#中模拟PostMan的POST请求操作
前置说明
以下代码默认匹配Postman中最常用的application/json类型POST请求,若你需要发送表单、文件、自定义Header等场景,调整对应请求参数即可。
1. HttpClient 实现(.NET官方推荐)
注意:不要每次请求都实例化新的HttpClient,建议使用静态单例或依赖注入框架提供的IHttpClientFactory管理实例,避免套接字资源耗尽。
using System.Net.Http; using System.Text; using System.Text.Json; // 建议将httpClient声明为静态全局变量,或者通过IHttpClientFactory获取 private static readonly HttpClient httpClient = new HttpClient(); public async Task<string> PostAsync(string url, object requestBody) { // 序列化请求体为JSON string json = JsonSerializer.Serialize(requestBody); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); // 按需添加Header,比如Authorization、Token等和Postman中一致的配置 // httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer 你的令牌"); HttpResponseMessage response = await httpClient.PostAsync(url, content); response.EnsureSuccessStatusCode(); // 确保响应状态码为成功区间 return await response.Content.ReadAsStringAsync(); }
2. WebClient 实现(已过时,仅兼容旧项目使用)
using System.Net; using System.Text; using System.Text.Json; public string PostWithWebClient(string url, object requestBody) { using (WebClient client = new WebClient()) { // 按需添加Header // client.Headers.Add("Authorization", "Bearer 你的令牌"); client.Headers.Add("Content-Type", "application/json"); string json = JsonSerializer.Serialize(requestBody); byte[] responseBytes = client.UploadData(url, "POST", Encoding.UTF8.GetBytes(json)); return Encoding.UTF8.GetString(responseBytes); } }
3. RestSharp 实现
使用前请先安装NuGet包:RestSharp
using RestSharp; public string PostWithRestSharp(string url, object requestBody) { var client = new RestClient(url); var request = new RestRequest(Method.Post); // 按需添加Header // request.AddHeader("Authorization", "Bearer 你的令牌"); request.AddJsonBody(requestBody); // 自动序列化对象为JSON,设置正确的Content-Type IRestResponse response = client.Execute(request); if (response.IsSuccessful) { return response.Content; } throw new Exception($"请求失败:{response.ErrorMessage}"); }
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

