c#HttpWebRequest POST’ing失败
所以我想尝试将内容发布到网络服务器上。
System.Net.HttpWebRequest EventReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("url"); System.String Content = "id=" + Id; EventReq.ContentLength = System.Text.Encoding.UTF8.GetByteCount(Content); EventReq.Method = "POST"; EventReq.ContentType = "application/x-www-form-urlencoded"; System.IO.StreamWriter sw = new System.IO.StreamWriter(EventReq.GetRequestStream(), System.Text.Encoding.UTF8); sw.Write(Content); sw.Flush(); sw.Close();
看起来没问题,我根据ENCODED数据的大小设置内容长度…无论如何,它在sw.flush()失败,“要写入流的字节数超过指定的内容长度大小”
StreamWriter在我背后做了一些魔法,我不知道吗? 有没有办法让我了解StreamWriter正在做什么?
其他答案已经解释了如何避免这种情况,但我想我会回答为什么会发生这种情况:你的实际内容之前会有一个字节顺序标记 。
您可以通过调用new UTF8Encoding(false)
而不是使用Encoding.UTF8
来避免这种情况。 这是一个展示差异的简短程序:
using System; using System.Text; using System.IO; class Test { static void Main() { Encoding enc = new UTF8Encoding(false); // Prints 1 1 // Encoding enc = Encoding.UTF8; // Prints 1 4 string content = "x"; Console.WriteLine(enc.GetByteCount("x")); MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms, enc); sw.Write(content); sw.Flush(); Console.WriteLine(ms.Length); } }
也许变得更容易:
using(WebClient client = new WebClient()) { NameValueCollection values = new NameValueCollection(); values.Add("id",Id); byte[] resp = client.UploadValues("url","POST", values); }
或者在这里查看允许使用的讨论:
client.Post(destUri, new { id = Id // other values here });
您无需显式设置ContentLength,因为当您关闭它时,它将自动设置为写入请求流的数据大小。