因此,我正在尝试将某些内容发布到网络服务器。
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。
您可以通过调用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);
}
}
关于C#HttpWebRequest POST失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1656717/