Python请求API正常,C#调用返回Invalid HTTP Request Input问题排查
问题:C#调用API返回
Invalid HTTP Request Input(Python调用正常) 现象
- Python环境下调用API可正常运行,代码如下:
requests.post(url , headers=headers, data=json.dumps(order))
- 使用C#实现相同请求时,API返回错误信息
Invalid HTTP Request Input。已通过Fiddler确认C#请求头包含Content-Type: application/json,但问题仍未解决,C#代码如下:
string serviceUrl = string.Format("{0}{1}", this._baseUri, uri); //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //serviceUrl = "http://mj.qzdyyy.com/ChsMobilePay/ChsMobilePayApi/v1/GetPayAuthNo"; HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl); byte[] buf = Encoding.GetEncoding("UTF-8").GetBytes(data); myRequest.Method = "POST"; myRequest.ContentLength = buf.Length; myRequest.KeepAlive = true; myRequest.Accept = "*/*"; if (headerDic != null && headerDic.Count != 0) { foreach (var item in headerDic) { if (item.Key == "ContentType") { myRequest.ContentType = item.Value; } else { myRequest.Headers.Add(item.Key, item.Value ); } } } //myRequest.Headers.Add("Content-Type", "application/json"); myRequest.ContentType = "application/json"; myRequest.AllowAutoRedirect = true; using (var stream = myRequest.GetRequestStream()) { stream.Write(buf, 0, buf.Length); } myResponse = (HttpWebResponse)myRequest.GetResponse(); using (myResponse = (HttpWebResponse)myRequest.GetResponse()) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd()); returnXml = reader.ReadToEnd(); reader.Close(); }
可能原因及解决方案
1. 请求体JSON格式或编码错误
Python中json.dumps(order)会生成标准JSON字符串,而C#中的data变量可能不是合法的JSON,或编码过程出现问题:
- 检查
data是否为严格符合JSON规范的字符串,比如引号转义、键值对格式是否正确。 - 推荐用序列化库生成JSON,比如Newtonsoft.Json的
JsonConvert.SerializeObject(yourObject),或.NET内置的System.Text.Json.JsonSerializer.Serialize(yourObject),避免手动拼接出错。
2. 重复获取响应流导致异常
C#代码中连续两次调用myRequest.GetResponse(),第一次获取后请求流已被读取,第二次调用会触发异常,可能干扰API的响应判断:
- 修改代码,只保留一次响应获取:
using (var myResponse = (HttpWebResponse)myRequest.GetResponse()) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); returnXml = reader.ReadToEnd(); reader.Close(); }
3. 请求头设置冲突
代码中先遍历headerDic设置ContentType,之后又手动覆盖myRequest.ContentType = "application/json";,若headerDic中已有ContentType,可能导致重复设置或逻辑混乱:
- 确保
headerDic中的头信息与手动设置无冲突,若headerDic已包含ContentType,移除后续手动设置的代码。
4. TLS协议版本不兼容
Python的requests默认支持较高版本的TLS协议,而旧版本.NET的HttpWebRequest可能默认使用低版本TLS,导致API拒绝请求:
- 取消注释并修改TLS设置代码:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
5. 请求内容长度计算偏差
若data包含隐藏字符,buf.Length可能与实际发送的内容长度不一致:
- 可以用
Encoding.UTF8.GetByteCount(data)确认字节数,或直接移除myRequest.ContentLength = buf.Length;,让HttpWebRequest自动处理内容长度。
内容的提问来源于stack exchange,提问作者jeffwu
相关产品推荐
相关产品推荐

