代码改变世界

必须先将 ContentLength 字节写入请求流,然后再调用 [Begin]GetResponse。解决方法

2016-08-16 17:45  NO.27  阅读(17130)  评论(0编辑  收藏  举报

当在后台实现POST请求的时候,出现如下错误:

 必须先将 ContentLength 字节写入请求流,然后再调用 [Begin]GetResponse。

或者是如下错误:

上述是因为由于我们使用的是代理服务器,那个还有一种原因不能忽略,就是如果目标网页的HTTP的版本号为1.0或之前的版本,而代理服务器的本版为1.1或以上。这么这是,代理服务器将不会转发我们的Post请求,并报错‍(417) Unkown

再看wireshark的包信息,其中明确可以看出,协议的版本号为HTTP1.1。这样,我们基本上可以确定‍(417) Unkown的原因:

握手失败,请求头域类型不匹配。

解决方法:

在配置文件加入

<configuration>

<system.net>

<settings>

           <servicePointManager expect100Continue="false" />

</settings>

</system.net>

</configuration>

或者在请求前加入如下代码:

System.Net.ServicePointManager.Expect100Continue = false;//默认是true,所以导致错误

 

附加两种请求方法:

方法一:

        public ActionResult b()
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            string Url = "http://xxx";
            string PostDataStr = string.Format("userName={0}&pwd={1}","a","b");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = PostDataStr.Length;
            
            StreamWriter write = new StreamWriter(request.GetRequestStream(),Encoding.ASCII);
            write.Write(PostDataStr);
            write.Flush();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding==null||encoding.Length<1) {
                encoding = "UTF-8";
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.GetEncoding(encoding));
            string retstring = reader.ReadToEnd();
            return Content(retstring);
        }

方法二:

        public async Task<ActionResult> a()
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            string postUrl = "http://xxx";
            var postContent = new FormUrlEncodedContent(new[]
                    {
                    new KeyValuePair<string, string>("userName", "a"),
                    new KeyValuePair<string, string>("pwd","b")

                    });
            var httpResponse = await new HttpClient().PostAsync(postUrl, postContent);
            var content = await httpResponse.Content.ReadAsStringAsync();
            return Content(content);
        }