C#中的HTTPS POST,Winforms(Stream Writer,HttpWebResponse,HttpWebRequest)

更新:我正在尝试将数据发布到https URI。 POST适用于HTTP,但HTTPS uri失败


嗨,我正在创建ac#winforms exe以将数据发布到网站。 代码如下。 问题是,流重复我的post数据..

例如:假设我想发布这个 – > username=bob

然后,当我检查流量时,实际发送的是, username=bobusername=bob

看到? 它重复,它再次将相同的行添加到缓冲区的末尾并发送它。

我试图在两天内找到这个问题我很疯狂..任何人都可以解决这个问题或者给我一些提示吗? 谢谢..

(内容长度正确设置为12,但在将相同数据再次附加到缓冲区尾部后,它会发送24个字节)

有标题

 POST /login/ HTTP/1.0 Content-Type: application/x-www-form-urlencoded Host: abc.test.com Content-Length: 12 username=bobusername=bob - 

这是我目前使用的代码

 string post_data = "username=bob"; string uri = "https://abc.test.com/login/"; HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri); request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; byte[] postBytes = Encoding.ASCII.GetBytes(post_data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postBytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postBytes, 0, postBytes.Length); MessageBox.Show(postBytes.Length.ToString()); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string tmp = sr.ReadToEnd().Trim(); 

我在行byte[] postBytes = Encoding.ASCII.GetBytes(post_data);postBytes包含正确的数据……但它输出两次。

为什么会这样? 我希望我很清楚..

我尝试了你的代码,在我将URI中的主机更改为可寻址的东西(使用http://adsf.com/login )之后,它似乎按预期工作(发送了带有12byte有效负载的HTTP Post)。 这是来自wireshark的踪迹:

Wireshark跟踪

您可以尝试使用我曾经看到的URI,这至少会排除您的计算机或代码作为问题的可能来源。 如果在使用不同的URI时问题消失,则问题可能出在网络设备和Web服务器之间(反向代理配置,Web服务器配置,网络交换机配置等)。

您可以尝试通过设置跟踪配置来获取更多信息,如本页所述 。 当我尝试你的代码时,我得到以下输出:

 System.Net Verbose: 0 : [2324] Data from ConnectStream#26756241::Write System.Net Verbose: 0 : [2324] 00000000 : 75 73 65 72 6E 61 6D 65-3D 62 6F 62 : username=bob System.Net Verbose: 0 : [2324] Exiting ConnectStream#26756241::Write() 

看起来数据已正确写入ConnectStream。 别的地方出了什么问题?

并且不要忘记关闭WebResponse对象。