C# HttpClient如何使用PostAsync方法发送带查询字符串的POST请求
问题原因
你给出的curl示例是将refId、productPrice参数放在URL查询字符串中,POST请求本身无请求体,你之前的两种方法均错误将参数放在请求体中,不符合接口要求因此返回404。同时你之前的代码里refId参数名多打了空格,也会导致参数识别失败。
正确实现代码
写法1(推荐,自动处理URL编码)
.NET Core 2.0+ / .NET 5+ 可直接使用QueryHelpers,无需额外引入包:
// 注意:HttpClient请全局单例声明,不要每次请求新建,避免套接字资源耗尽 private static readonly HttpClient _httpClient = new HttpClient(); public async Task SendPostRequest() { string baseUrl = "http://mywebsite.com/api/CompleteService"; var queryParams = new Dictionary<string, string> { {"refId", "12345"}, {"productPrice", "600"} }; // 拼接带查询参数的完整请求URL string requestUrl = QueryHelpers.AddQueryString(baseUrl, queryParams); // 添加Accept请求头,对应curl的--header 'Accept: application/json' _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); // POST无请求体,第二个参数传null即可 HttpResponseMessage response = await _httpClient.PostAsync(requestUrl, null); // 处理响应结果 if (response.IsSuccessStatusCode) { string responseContent = await response.Content.ReadAsStringAsync(); // 你的业务逻辑 } }
写法2(无额外依赖)
如果不想使用QueryHelpers,也可以用FormUrlEncodedContent转换参数后拼接URL:
private static readonly HttpClient _httpClient = new HttpClient(); public async Task SendPostRequest() { string baseUrl = "http://mywebsite.com/api/CompleteService"; var queryParams = new Dictionary<string, string> { {"refId", "12345"}, {"productPrice", "600"} }; using var formContent = new FormUrlEncodedContent(queryParams); string queryStr = await formContent.ReadAsStringAsync(); string requestUrl = $"{baseUrl}?{queryStr}"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await _httpClient.PostAsync(requestUrl, null); // 后续处理响应逻辑同上 }
原有写法错误说明
- 方法1错误:将查询参数格式的字符串以JSON格式放入请求体,接口未设计接收请求体参数,同时拼接参数时
refId后多写了空格导致参数名错误。 - 方法2错误:将参数放入表单格式的请求体而非URL查询字符串中,同样不符合接口要求,且字典中
refId键后多了空格导致参数名匹配失败。
内容的提问来源于stack exchange,提问作者Jay 鲍昱彤
相关产品推荐
相关产品推荐

