![](/img/trans.png)
[英]Which specific status codes cause a WebException to be thrown by HttpWebRequest.GetResponse()?
[英]HttpWebRequest - GetResponse() - WebException ReceiveFailure
我有一個 WCF 服務,它每分鍾運行頻繁(1000+)個到外部 API 的出站連接。
我的代碼經常拋出以下異常,但並不總是顯示這是一個 WebException,其 WebException 狀態屬性為ReceiveFailure
發出出站請求的代碼如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(paramBuilder.ToString());
request.ServicePoint.ConnectionLeaseTimeout = 0;
request.Method = "GET";
request.Timeout = 33000; //33 Second Timeout Is By Design
Stream stream = default(Stream);
HttpWebResponse response = default(HttpWebResponse);
try
{
response = (HttpWebResponse) request.GetResponse();
stream = response.GetResponseStream();
reader = new StreamReader(stream,Encoding.UTF8);
string str = reader.ReadToEnd();
return str;
}
catch (WebException exception)
{
//Handle WebException
}
catch (Exception exception)
{
//Handle Exception
}
finally
{
if (reader != null)
reader.Dispose();
if (response != null)
response.Close();
if (stream != null)
stream.Dispose();
}
異常堆棧跟蹤顯示異常是由 GetResponse() 引起的。
我偶爾會收到一個 WebException -ReceiveFailure,這可能是什么原因造成的。
我已經參考了有關此狀態的 MSDN 文檔,但這對我沒有幫助。
在這里暗中拍攝...
在等待響應時有一個特殊情況:如果系統時鍾是由 Windows 時間服務自動設置的,或者是手動設置的,您可能會遇到一些不可預知的結果。
如果您通過 HTTPS 發送您的請求,那么您可能會遇到錯誤地作為 ReceiveFailure 拋出的常規超時。
查看這篇文章了解更多信息: http : //support.microsoft.com/kb/2007873
我有一個相關的問題,我在尋找解決方案時意識到了一些事情。
WebExceptionStatus
enum
不等同於您調用的 API 返回的 http 狀態代碼。 相反,它是在 http 調用期間可能發生的可能錯誤的枚舉。WebExceptionStatus
錯誤代碼是WebExceptionStatus.ProtocolError
又名數字 7 作為 int。WebException.Status
是否為WebExceptionStatus.ProtocolError
。 然后你可以從WebExceptionStatus.Response
獲取真正的響應並讀取其內容。WebException.Status
是否是WebExceptionStatus.Timeout
這是一個例子:
try
{
...
}
catch (WebException webException)
{
if (webException.Status == WebExceptionStatus.ProtocolError)
{
var httpResponse = (HttpWebResponse)webException.Response;
var responseText = "";
using (var content = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = content.ReadToEnd(); // Get response body as text
}
int statusCode = (int)httpResponse.StatusCode; // Get the status code
}
else if (webException.Status == WebExceptionStatus.ProtocolError)
{
// Timeout handled by your code. You do not have a response here.
}
// Handle other webException.Status errors. You do not have a response here.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.