c#HttpWebRequest POST’ing failed

前端之家收集整理的这篇文章主要介绍了c#HttpWebRequest POST’ing failed前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我正在尝试向网络服务器发送一些东西. @H_301_2@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()中失败,“要写入流的字节超过指定的Content-Length大小”

StreamWriter在我背后做了一些魔术,我不知道吗?有没有办法我可以同意StreamWriter在做什么?

解决方法

其他的答案已经解释了如何避免这种情况,但是我以为我会回答为什么会发生这样的事情:在你的实际内容之前,你会结束一个 byte order mark.

您可以通过调用新的UTF8Encoding(false)而不是使用Encoding.UTF8来避免这种情况.这是一个简短的程序来证明差异:

@H_301_2@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); } }

猜你在找的C&C++相关文章