错误(HttpWebRequest):写入流的字节超过指定的Content-Length字节大小
本文关键字:字节 Content-Length 错误 HttpWebRequest | 更新日期: 2023-09-27 18:12:22
我似乎不明白为什么我总是得到以下错误:
Bytes to be written to the stream exceed the Content-Length bytes size specified.
:
writeStream.Write(bytes, 0, bytes.Length);
这是一个Windows窗体项目。如果有人知道这里发生了什么,我肯定欠你一个人情。
private void Post()
{
HttpWebRequest request = null;
Uri uri = new Uri("xxxxx");
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
XmlDocument doc = new XmlDocument();
doc.Load("XMLFile1.xml");
request.ContentLength = doc.InnerXml.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(doc.InnerXml);
writeStream.Write(bytes, 0, bytes.Length);
}
string result = string.Empty;
request.ProtocolVersion = System.Net.HttpVersion.Version11;
request.KeepAlive = false;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
}
catch (Exception exp)
{
// MessageBox.Show(exp.Message);
}
}
有三个可能的选项
-
修复@rene
回答中描述的ContentLength 不要设置ContentLength, HttpWebRequest正在缓冲数据,并自动设置ContentLength
SendChunked属性设置为true,不设置ContentLength。将请求发送块编码到web服务器。(需要HTTP 1.1并且必须被web服务器支持)
...
request.SendChunked = true;
using (Stream writeStream = request.GetRequestStream())
{ ... }
来自InnerXml的编码字节数组可能更长,因为UTF8编码中的某些字符占用2或3个字节。
修改代码如下:
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(doc.InnerXml);
request.ContentLength = bytes.Length;
writeStream.Write(bytes, 0, bytes.Length);
}
要准确显示正在发生的事情,请在LINQPad中尝试:
var s = "é";
s.Length.Dump("string length");
Encoding.UTF8.GetBytes(s).Length.Dump("array length");
这将输出:
string length: 1
array length: 2
,现在使用不带撇号的e
:
var s = "e";
s.Length.Dump("string length");
Encoding.UTF8.GetBytes(s).Length.Dump("array length");
将输出:
string length: 1
array length: 1
所以请记住:字符串长度和特定编码所需的字节数可能不同。