我花了一整天的时间试图弄清楚我昨天做错了什么。来这里尝试寻求帮助。当我运行实际的 GetResponse 时会触发跟随错误。我是 API 的新手,所以我确定我错过了一些真正简单的东西。
You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.
这是我用来尝试将 JSON 发送到 API 的代码。付款对象只有输入的表单值和在商家端使用正确帐户的凭据。
var json = JsonConvert.SerializeObject(payment);
var apiUrl = new Uri($"Removed endpoint URL");
var postBytes = Encoding.UTF8.GetBytes(json);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = postBytes.Length;
httpWebRequest.AllowWriteStreamBuffering = false;
//This is where the error triggers and drops to the catch.
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
我提前感谢任何帮助,我可能完全错了,这是我试图解决通话问题的一系列事情。
除非我错过了,否则您实际上HttpWebRequest
并没有在发送之前将有效负载数据写入正文。
using (Stream _reqStrm = httpWebRequest.GetRequestStream())
{
_reqStrm.Write(postBytes, 0, postBytes.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
....
不相关,但如果可以,请考虑HttpClient
嗯..
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句