C#学习教程:Error(HttpWebRequest):写入流的字节数超过了指定的Content-Length字节大小words我似乎无法弄清楚为什么我不断收到以下错误:要写入流的字节超过指定的Content-Length字节大小。线上:writeStream.Write(bytes,0,bytes.Length);这是一个Windows窗体项目。如果有人知道这里发生了什么,我绝对欠你一个。privatevoidPost(){HttpWebRequest请求=null;uriuri=newUri("xxxxx");请求=(HttpWebRequest)WebRequest.Create(uri);request.Method="POST";request.ContentType="application/x-www-form-urlencoded";XmlDocumentdoc=newXmlDocument();doc.Load("XMLFile1.xml");request.ContentLength=doc.InnerXml.Length;使用(StreamwriteStream=request.GetRequestStream()){UTF8Encoding编码=newUTF8Encoding();byte[]bytes=encoding.GetBytes(doc.InnerXml);writeStream.Write(bytes,0,bytes.Length);}字符串结果=string.Empty;request.ProtocolVersion=System.Net.HttpVersion.Version11;请求.KeepAlive=false;尝试{使用(HttpWebResponse响应=(HttpWebResponse)request.GetResponse()){使用(StreamresponseStream=response.GetResponseStream()){使用(System.IO.StreamReaderreadStream=newSystem.IO.StreamReader(responseStream,Encoding.UTF8)){结果=readStream.ReadToEnd();}}}}catch(Exceptionexp){//消息geBox.Show(exp.Message);有三种可能的选项代码:...request.SendChunked=true;使用(StreamwriteStream=request.GetRequestStream()){...}InnerXml中的编码字节数组可能更长,因为UTF8编码中的某些字符占用单个字符的2或3个字节更改代码如下:使用(StreamwriteStream=request.GetRequestStream()){UTF8Encoding编码=newUTF8Encoding();byte[]bytes=encoding.GetBytes(doc.InnerXml);request.ContentLength=bytes.Length;writeStream.Write(bytes,0,bytes.Length);}要准确显示发生了什么,请在LINQPad中试试这个:vars="é";s.Length.Dump("字符串长度");Encoding.UTF8.GetBytes(s).Length.Dump("数组长度");这将输出:stringlength:1arraylength:2nowUsingewithouttheapostrophe:vars="e";s.Length.Dump("字符串长度");Encoding.UTF8.GetBytes(s).Length.Dump("数组长度");这将输出:stringlength:1arraylength:1请记住:特定编码所需的字符串长度和字节数可能会有所不同。以上是C#学习教程:Error(HttpWebRequest):ThenumberofbytestobewrittentothestreamexceedsthespecifiedContent-Lengthbytesize.请注意——本文摘自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
