关于HttpWebResponse,写一个post方法,必须先将 ContentLength 字节写入请求流,

.Net技术 码拜 8年前 (2016-05-13) 1626次浏览
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 "";
            }
        }
    }
}
解决方案

10

不要设置ContentLength

20

引用:
Quote: 引用:

不要设置ContentLength

问题解决了= =但是本人还是很好奇为什么不能设置这个,本人设置的长度和本人的字段长度是一致的呀

一致个屁,你写的长度和设置的长度方法用的都不一样

10

关键现在http协议规定必须有contentlength,所以就算你不设置,系统也会帮你加上,根本不需要关心这个

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于HttpWebResponse,写一个post方法,必须先将 ContentLength 字节写入请求流,
喜欢 (0)
[1034331897@qq.com]
分享 (0)