9

所以我正在尝试将某些内容发布到网络服务器。

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 正在做什么?

4

3 回答 3

23

其他答案已经解释了如何避免这种情况,但我想我会回答为什么会这样:你最终会在实际内容之前得到一个字节顺序标记。

您可以通过调用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);
    }

}
于 2009-11-01T09:36:46.543 回答
4

也许让喜欢更容易:

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
 });
于 2009-11-01T09:22:39.477 回答
2

您无需显式设置 ContentLength,因为当您关闭它时,它将自动设置为写入请求流的数据大小。

于 2009-11-01T09:26:49.313 回答