C#如何为POST请求添加JSON请求体 WebRequest传参无效问题咨询
解决方案
你当前的代码仅配置了请求的ContentType和请求方法,没有将JSON请求体写入请求的输出流中,因此服务端无法收到提交的参数。
基于现有WebRequest的修正代码
// 注意原URL格式错误,缺少双斜杠 string ClaimStatus_url = "https://xyz"; WebRequest request = WebRequest.Create(ClaimStatus_url); request.ContentType = "application/json"; request.Method = "POST"; // 1. 构造请求体内容,转成UTF8字节数组 string postBody = "{\"ClaimNo\":\"123123\"}"; // 推荐用JSON序列化库生成,避免手动拼写JSON出现语法错误 byte[] postBytes = Encoding.UTF8.GetBytes(postBody); // 2. 设置请求内容长度,告知服务端需要读取的字节数 request.ContentLength = postBytes.Length; // 3. 将JSON内容写入请求流 using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(postBytes, 0, postBytes.Length); } // 所有可释放资源建议用using自动管理,避免资源泄漏 using (WebResponse response = request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8)) { string result = reader.ReadToEnd(); // 处理返回结果 }
更推荐的实现方式(使用HttpClient)
WebRequest是.NET早期的遗留API,微软官方已经标记为过时,新开发项目推荐使用性能更高、API更易用的HttpClient。
// HttpClient建议全局静态初始化,不要每次请求都新建实例,避免端口耗尽问题 private static readonly HttpClient _httpClient = new HttpClient(); public async Task<string> GetClaimStatusAsync() { // 用匿名对象构造参数,自动序列化避免手动拼写JSON错误 var requestBody = new { ClaimNo = "123123" }; string jsonBody = System.Text.Json.JsonSerializer.Serialize(requestBody); var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("https://xyz", content); // 校验请求是否成功,失败会抛出异常,也可自行判断状态码处理 response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); }
内容的提问来源于stack exchange,提问作者Shreyash Mohite
相关产品推荐
相关产品推荐

