关于HttpWebResponse,写一个post方法,必须先将 ContentLength 字节写入请求流,然后再调用 [Begin]GetResponse

Canonzki 2016-07-27 11:29:58

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace TestCon
{
static class BillInfo
{
public static string BillInfo_Post_Get(string Post_String,string Post_Data) {
try {
string s_Connection_String = Post_String;
HttpWebRequest BillInfo_Request = (HttpWebRequest)WebRequest.Create(s_Connection_String);
BillInfo_Request.Method = "POST";
BillInfo_Request.ContentType = "application/x-www-form-urlencoded";
BillInfo_Request.ContentLength = s_Connection_String.Length;
BillInfo_Request.Timeout = 20000;

Stream BillInfo_Stream = BillInfo_Request.GetRequestStream();

BillInfo_Stream.Write(Encoding.UTF8.GetBytes(Post_Data), 0, Encoding.UTF8.GetBytes(Post_Data).Length);


HttpWebResponse BillInfo_Response = (HttpWebResponse)BillInfo_Request.GetResponse();


StreamReader BillInfo_Reader = new StreamReader(BillInfo_Response.GetResponseStream(), Encoding.UTF8);

return BillInfo_Reader.ReadToEnd();
}
catch (System.Exception ex) {
Console.WriteLine(ex);
Console.ReadLine();
return "";
}
}
}
}


...全文
1074 6 打赏 收藏 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Canonzki 2016-07-27
  • 打赏
  • 举报
回复
引用 4 楼 shingoscar 的回复:
引用 3 楼 Canonzki 的回复:
[quote=引用 2 楼 shingoscar 的回复:] 不要设置ContentLength
问题解决了= =但是我还是很好奇为什么不能设置这个,我设置的长度和我的字段长度是一致的呀
一致个屁,你写的长度和设置的长度方法用的都不一样[/quote]原来是这样,想明白了= =一个返回的是字串长度一个返回的是字节数= =受教了
Poopaye 2016-07-27
  • 打赏
  • 举报
回复
关键现在http协议规定必须有contentlength,所以就算你不设置,系统也会帮你加上,根本不需要关心这个
Poopaye 2016-07-27
  • 打赏
  • 举报
回复
引用 3 楼 Canonzki 的回复:
引用 2 楼 shingoscar 的回复:
不要设置ContentLength
问题解决了= =但是我还是很好奇为什么不能设置这个,我设置的长度和我的字段长度是一致的呀
一致个屁,你写的长度和设置的长度方法用的都不一样
Canonzki 2016-07-27
  • 打赏
  • 举报
回复
引用 2 楼 shingoscar 的回复:
不要设置ContentLength
问题解决了= =但是我还是很好奇为什么不能设置这个,我设置的长度和我的字段长度是一致的呀
Poopaye 2016-07-27
  • 打赏
  • 举报
回复
不要设置ContentLength
Canonzki 2016-07-27
  • 打赏
  • 举报
回复
一直提示我 必须先将 ContentLength 字节写入请求流,然后再调用 [Begin]GetResponse。

111,128

社区成员

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

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

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