System.Net.WebException: 操作超時


C# 提交網頁請求時出現如下錯誤: System.Net.WebException: 操作超時

 

原因一:

連接超時時間 Timeout 以及寫入Post數據超時時間 ReadWriteTimeout 設置得太短,一般要設置大於6000ms。

 

原因二:

Expect100Continue 屬性的值設置為了true,將 Expect100Continue 屬性的值設置為 false 即可解決問題。

 

 

代碼:

public static string Post(string xml, string url, bool isUseCert, int timeout)
{
System.GC.Collect();//垃圾回收,回收沒有正常關閉的http連接

string result = "";//返回結果

HttpWebRequest request = null;
HttpWebResponse response = null;
Stream reqStream = null;

try
{
//設置最大連接數
ServicePointManager.DefaultConnectionLimit = 200;
//設置https驗證方式
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
}

/***************************************************************
* 下面設置HttpWebRequest的相關屬性
* ************************************************************/
request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "POST";
request.Timeout = timeout * 1000;

//設置代理服務器
//WebProxy proxy = new WebProxy(); //定義一個網關對象
//proxy.Address = new Uri(WxPayConfig.PROXY_URL); //網關服務器端口:端口
//request.Proxy = proxy;

//設置POST的數據類型和長度
request.ContentType = "text/xml";
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
request.ContentLength = data.Length;

//這個在Post的時候,一定要加上,如果服務器返回錯誤,他還會繼續再去請求,不會使用之前的錯誤數據,做返回數據
request.ServicePoint.Expect100Continue = false;

//是否使用證書
if (isUseCert)
{
string path = HttpContext.Current.Request.PhysicalApplicationPath;
X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);
request.ClientCertificates.Add(cert);
Log.Debug("WxPayApi", "PostXml used cert");
}

//往服務器寫入數據
reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();

//獲取服務端返回
response = (HttpWebResponse)request.GetResponse();

//獲取服務端返回數據
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = sr.ReadToEnd().Trim();
sr.Close();
}
catch (System.Threading.ThreadAbortException e)
{
Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
Log.Error("Exception message: {0}", e.Message);
System.Threading.Thread.ResetAbort();
}
catch (WebException e)
{
Log.Error("HttpService", e.ToString());
if (e.Status == WebExceptionStatus.ProtocolError)
{
Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
}
throw new WxPayException(e.ToString());
}
catch (Exception e)
{
Log.Error("HttpService", e.ToString());
throw new WxPayException(e.ToString());
}
finally
{
//關閉連接和流
if (response != null)
{
response.Close();
}
if(request != null)
{
request.Abort();
}
}
return result;
}


免責聲明!

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



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