HTTP_INTERNAL_ERROR(500)不是可以創建錯誤流的唯一響應代碼,還有許多其他的:400,401,402,403,404,405,406,407,408,409,410,411 ,412,413,414,415,501,502,503,504,505等。
不僅如此,而且connection.getResponseCode()
可能會在引發連接並且HTTP響應狀態碼是錯誤處理的情況下拋出異常,類狀態碼。因此,在connection.getResponseCode()
之後立即檢查500(HTTP_INTERNAL_ERROR)可能實際上是無法訪問的代碼,具體取決於您如何訪問connection
。
我見過的策略是在引發異常時使用錯誤流,否則使用輸入流。以下代碼提供了基本結構起點。你可能會想添加到它。
InputStream responseStream = null;
int responseCode = -1;
IOException exception = null;
try
{
responseCode = connection.getResponseCode();
responseStream = connection.getInputStream();
}
catch(IOException e)
{
exception = e;
responseCode = connection.getResponseCode();
responseStream = connection.getErrorStream();
}
// You can now examine the responseCode, responseStream, and exception variables
// For example:
if (responseStream != null)
{
// Go ahead and examine responseCode, but
// always read the data from the responseStream no matter what
// (This clears the connection for reuse).
// Probably log the exception if it's not null
}
else
{
// This can happen if e.g. a malformed HTTP response was received
// This should be treated as an error. The responseCode variable
// can be examined but should not be trusted to be accurate.
// Probably log the exception if it's not null
}
我認爲它必須與響應代碼,但我不太確定。謝謝。 – Rcunn87 2012-02-27 20:35:54
user384706的回答不處理所有情況。 HTTP_INTERNAL_ERROR(500)不是唯一可以創建錯誤流的響應代碼。而且,當響應代碼是4xx或5xx時,HttpURLConnection喜歡拋出異常。查看我的答案瞭解更多詳情。 – 2012-02-27 20:58:03
我只是注意到,因爲我正在更多地研究它。 – Rcunn87 2012-02-27 21:17:59