2009-11-18 57 views
1

这是推动我坚果:为什么我在执行HTTP POST时耗尽流的字节?

WebRequest request = WebRequest.Create(url); 
    request.Method = "POST"; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.ContentLength = Encoding.UTF8.GetByteCount(data); 
    Stream reqs = request.GetRequestStream(); 
    StreamWriter stOut = new StreamWriter(reqs, Encoding.UTF8); 
    stOut.Write(data); 
    stOut.Flush(); 

,我感到我已经用完流中的字节的例外......但我已经使用了相同的编码得到的字节数!

使用ASCII这不会失败。 这是因为Windows喜欢添加的UTF-8 BOM吗?

+0

如果你只是把'.ContentLength ='赋值出去了会发生什么? AFAIK应该在发送请求之前自动确定“ContentLength”。 – dtb 2009-11-18 21:30:25

+0

跳过.ContentLength赋值工作。 – Broam 2009-11-18 22:25:13

回答

3

这可能是BOM;尝试使用没有BOM的明确编码:

Encoding enc = new UTF8Encoding(false); 
... 
request.ContentLength = enc.GetByteCount(data); 
... 
StreamWriter stOut = new StreamWriter(reqs, enc); 

更简单;改为切换到WebClient,并尝试自己处理;这是很容易张贴这个形式:

using (var client = new WebClient()) 
    { 
     var data = new NameValueCollection(); 
     data["foo"] = "123"; 
     data["bar"] = "456"; 
     byte[] resp = client.UploadValues(address, data); 
    } 

或者与代码from here

byte[] resp = client.Post(address, new {foo = 123, bar = 546}); 
+0

最简单的做法是跳过内容长度分配......但这绝对是由于BOM。 – Broam 2009-11-18 22:25:48

+0

使用显式编码对象工作。 – Broam 2009-11-18 22:28:35

1

您也可以尝试这样的事:

byte[] bytes = Encoding.UTF8.GetBytes(data); 

request.ContentLength = bytes.Length; 
request.GetRequestStream().Write(bytes, 0, bytes.Length); 
1

不要忘记实际上是对数据进行网址编码,就像您在ContentType中所承诺的一样。这是一个单行的:

byte[] bytes = System.Web.HttpUtility.UrlEncodeToBytes(data, Encoding.UTF8); 
相关问题