C# 類比post資料提交時 出現如下錯誤: System.Net.WebException: 遠程伺服器返回錯誤: (417) Expectation Failed 的解決辦法

來源:互聯網
上載者:User

一般情況的代碼,重點在出錯的那段代碼,其他的代碼可以根據自己的情況寫相應的代碼:

HttpWebRequest req=WebRequest.Create(url1) as HttpWebRequest;
   req.Method="POST";
   req.Accept="application/json, text/javascript, */*";
   req.Referer=url2;

   req.UserAgent="Mozilla/4.0";
   req.ContentType="application/x-www-form-urlencoded";
   req.CookieContainer=cookie;
   req.KeepAlive=true;
   string postString="uname=ioriliaotest3&" +
                  "password=19850420&" +
                  "passwordconf=19850420" +
                  "&mobile=&verifycode="+
                   HttpUtility.UrlEncode(textBox1.Text,encoding)+
                  "&dmain=163.com&version=regvf1";
   byte[] postByte=Encoding.ASCII.GetBytes(postString);
   Stream reqStream=req.GetRequestStream();
   reqStream.Write(postByte,0,postByte.Length);
   reqStream.Close();
   HttpWebResponse resp=req.GetResponse() as HttpWebResponse;//出錯 WebException: 遠程伺服器返回錯誤: (417) Expectation Failed
   Stream respStream=resp.GetResponseStream();
   StreamReader respReader=new StreamReader(respStream,encoding);
   richTextBox1.AppendText(respReader.ReadToEnd());
   respStream.Close();
   respReader.Close();

歸納其原因:
httpwebrequest控制項有一個透明過程,先向服務方查詢url是否存在而不發送POST的內容,伺服器如果證實url是可訪問的,才發送POST,早期的Apache就認為這是一種錯誤,而IIS卻可以正確應答

解決方案:

寫.net程式時在始化代碼中,或者設定檔app.config之類的檔案中
加下這麼一句就可以了

ServicePointManager.Expect100Continue = false;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.