KJ *_*dis 9 c# webrequest httpwebrequest streamwriter
所以我正试图将一些东西发布到网络服务器上.
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();
Run Code Online (Sandbox Code Playgroud)
看起来没问题,我根据ENCODED数据的大小设置内容长度...无论如何,它在sw.flush()失败,"要写入流的字节超过指定的内容长度大小"
StreamWriter在我背后做了一些魔法,我不知道吗?有没有办法让我了解StreamWriter正在做什么?
Jon*_*eet 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);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11440 次 |
最近记录: |