写入流的字节超出指定的Content-Length字节大小

tlj893 2016-02-27 04:12:34
百度、Google了好多,依旧未能解决。
POST的函数如下
private void DeleteLesson(string kch)
{
string url = "省略网址";
string postData = "kch=“ + kch + ”&kxh=1001&xh=&uid=41356032";
byte[] byteResquest = Encoding.GetEncoding("gb2312").GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.ContentLength = postData.Length;
MessageBox.Show(postData.Length.ToString()); //下面有弹窗
MessageBox.Show(byteResquest.Length.ToString()); //下面有弹窗
req.CookieContainer = Whole.requestCookie; //cookie
req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
req.KeepAlive = true;
req.Method = WebRequestMethods.Http.Post;

Stream stream;
stream = req.GetRequestStream();
stream.Write(byteResquest, 0, byteResquest.Length);
stream.Close();

HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
string htmlCharset = "utf-8";
Encoding htmlEncoding = Encoding.GetEncoding(htmlCharset);
StreamReader sr = new StreamReader(rep.GetResponseStream(), htmlEncoding);
string repHtml = sr.ReadToEnd();
}


然后就出现了错误:
先是两个设定的弹窗


两个明明都是37,为什么还会提示“写入流的字节超出指定的Content-Length字节大小”?

下面是异常文本
有关调用实时(JIT)调试而不是此对话框的详细信息,
请参见此消息的结尾。

************** 异常文本 **************
System.Net.ProtocolViolationException: 写入流的字节超出指定的 Content-Length 字节大小。
在 System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
在 System.Net.ConnectStream.Write(Byte[] buffer, Int32 offset, Int32 size)
在 TGR.Choose.PostLesson(String id)
在 TGR.Choose.DeleteLesson(String kch)
在 TGR.Choose.LessonList_MouseDoubleClick(Object sender, MouseEventArgs e)
在 System.Windows.Forms.ListBox.WndProc(Message& m)
在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** 已加载的程序集 **************


尝试过将GB2313换成UTF-8,但还是出错
...全文
1511 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
jyxzfw 2016-10-11
  • 打赏
  • 举报
回复
很有帮助
Justin-Liu 2016-02-29
  • 打赏
  • 举报
回复
转化成byte的长度
tcmakebest 2016-02-28
  • 打赏
  • 举报
回复
要这样用, 长度是按照字节算的, 不是字符, 也许楼主是看花眼了 req.ContentLength = byteResquest.Length;
Poopaye 2016-02-27
  • 打赏
  • 举报
回复
堆栈明明是PostLesson,你这是什么?
Jaye-L 2016-02-27
  • 打赏
  • 举报
回复
把 req.ContentLength = postData.Length; 去掉试试~

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧