必須先將 ContentLength 字節寫入請求流,然后再調用 [Begin]GetResponse。解決方法


當在后台實現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);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM