求助:如何在C#中通过HttpWebRequest发送API POST请求?
使用C#的HttpWebRequest发送API POST请求
嘿,你已经搭好了基础框架,我来帮你把这段发送POST请求的代码补全优化,让它能正确和API交互~
下面是完整的可运行代码,包含了请求头设置、请求体处理、响应读取和异常捕获:
using System; using System.IO; using System.Net; using System.Text; class ApiPostRequestExample { static void SendPostRequest() { try { // 初始化请求实例 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://www.etc.com/c/search"); // 设置请求方法和连接属性 webRequest.Method = "POST"; webRequest.Connection = "keep-alive"; webRequest.KeepAlive = true; // 和Connection: keep-alive对应,建议启用以复用连接 // 关键:设置Content-Type头,告诉服务器我们发送的是JSON格式 webRequest.ContentType = "application/json; charset=utf-8"; // 构造你的JSON请求体(替换成实际的业务数据) string postJson = "{\"contains\":true, \"yourKey\":\"yourValue\"}"; byte[] postDataBytes = Encoding.UTF8.GetBytes(postJson); // 设置请求体的字节长度,这一步很重要,服务器依赖它接收数据 webRequest.ContentLength = postDataBytes.Length; // 将请求体写入请求流 using (Stream requestStream = webRequest.GetRequestStream()) { requestStream.Write(postDataBytes, 0, postDataBytes.Length); } // 发送请求并获取响应 using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse()) { // 读取响应内容 using (StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { string responseContent = responseReader.ReadToEnd(); Console.WriteLine("API返回内容:\n" + responseContent); } // 可以查看响应的状态码,确认请求是否成功 Console.WriteLine("\n响应状态码: " + (int)response.StatusCode + " - " + response.StatusDescription); } } catch (WebException ex) { // 处理网络错误或API返回的错误状态码(比如400、500) Console.WriteLine("请求出错: " + ex.Message); if (ex.Response != null) { using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response) { Console.WriteLine("错误状态码: " + (int)errorResponse.StatusCode); using (StreamReader errorReader = new StreamReader(errorResponse.GetResponseStream())) { string errorDetails = errorReader.ReadToEnd(); Console.WriteLine("错误详情:\n" + errorDetails); } } } } catch (Exception ex) { Console.WriteLine("其他异常: " + ex.Message); } } }
几个关键细节说明
- Content-Type头:这是发送JSON请求的核心配置,如果不设置,服务器大概率无法正确解析你的请求体,一定要加上
application/json; charset=utf-8。 - 请求体长度:必须设置
ContentLength为请求体字节数组的长度,否则服务器可能会中断连接或者无法接收完整数据。 - 资源释放:所有流对象都用
using包裹,这样能自动释放资源,避免内存泄漏。 - 身份验证(可选):如果你的API需要验证,比如你注释掉的
Credentials和PreAuthenticate,可以根据API要求开启,比如基本验证:webRequest.Credentials = new NetworkCredential("你的用户名", "你的密码"); webRequest.PreAuthenticate = true;
内容的提问来源于stack exchange,提问作者MD.Tofael Ahmed
相关产品推荐
相关产品推荐

