我试图从C#中的其他WS获取一些数据,但我收到此错误:"您必须在调用[Begin]之前将ContentLength字节写入请求流的GetResponse "
这是我尝试使用的代码:
var json = new JavaScriptSerializer().Serialize(order);
string jsonResponseToString = "";
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("https://myurl.com");
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(json);
request.ContentLength = byteArray.Length;
request.ContentType = @"application/json";
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
Stream str = response.GetResponseStream();
var sr = new StreamReader(str, encoding);
jsonResponseToString = sr.ReadToEnd();
var result = new OrderResult();
result = new JavaScriptSerializer().Deserialize<OrderResult>(jsonResponseToString);
if (str != null)
{
str.Flush();
str.Close();
}
}
}
catch (WebException ex)
{
//
}
错误发生在这一行:
using (var response = (HttpWebResponse)request.GetResponse())
我知道如何解决这个问题,我做错了吗?
提前致谢,Laziale
答案 0 :(得分:0)
由于错误试图告诉您,您需要在发送之前将字节写入请求。
调用GetRequestStream()
并写下你的字节。