所以我正在尝试向网络服务器发送一些东西.
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来避免这种情况.这是一个简短的程序来证明差异:
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); } }
原文地址:https://www.jb51.cc/c/115954.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。