今天用了將近一天的時間來查找這個問題的存在,不停的百度查找緣由測試緣由,發現解決方案非常簡單,不過最好還好哦啊都解決了,在這裏紀錄一下,但願能夠幫到大家html
payload = System.Text.Encoding.UTF8.GetBytes(postDataStr); request.ContentLength = payload.Length; Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); //writer.Flush(); writer.Close(); //HttpWebResponse response = (HttpWebResponse)request.GetResponse(); HttpWebResponse res; try { System.Net.ServicePointManager.DefaultConnectionLimit = 200; res = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { res = (HttpWebResponse)ex.Response; }
今天個人res 一直報操做超時,百度了不少方案,一一測試,總結來講,若是你也出現了這種錯誤,能夠一次嘗試一下方案服務器
第一種:加長request的timeout的時間,默認是100秒(我就是測試了好多方案,才發現個人timeout的時間過短,引發的操做超時)app
第二種:設置request.KeepAlive = false;緣由是:默認KeepAlive的屬性是true,將此屬性設置爲 true 以發送帶有 Keep-alive 值的 Connection HTTP 標頭。 應用程序使用 KeepAlive 指示持久鏈接的首選項。 當 KeepAlive 屬性爲 true 時,應用程序與支持它們的服務器創建持久鏈接。也要記住要及時關閉相對應的關閉工做post
if (request != null) { request.Abort(); } if (res != null) { res.Close(); }
第三種:測試
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
加上這句話,由於這個默認設置的是2,當http的鏈接超過2條時,也會報這種操做超時的錯誤url
第四種:spa
System.GC.Collect(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postDataStr.Length; request.KeepAlive = false; request.Timeout = 6000000;
在code
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
以前加上:System.GC.Collect();orm
緣由是:系統中的http相關的資源沒有正確的釋放,致使後續的GetResponse或者說GetRequestStream超時死掉htm
改進以後的全部代碼:
public static bool HttpPost(string Url, string postDataStr, out string errMsg, out string returnData) { try { System.GC.Collect(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postDataStr.Length; request.KeepAlive = false; request.Timeout = 6000000; //StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.UTF8); //writer.Write(postDataStr); //writer.Flush(); byte[] payload; payload = System.Text.Encoding.UTF8.GetBytes(postDataStr); request.ContentLength = payload.Length; Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); //writer.Flush(); writer.Close(); //HttpWebResponse response = (HttpWebResponse)request.GetResponse(); HttpWebResponse res; try { System.Net.ServicePointManager.DefaultConnectionLimit = 200; res = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { res = (HttpWebResponse)ex.Response; } //StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); string retString = reader.ReadToEnd(); errMsg = ""; try { returnData = Util.base642Str(retString); } catch (Exception) { returnData = retString; //throw; } if (request != null) { request.Abort(); } if (res != null) { res.Close(); } return true; }