2012-02-27 24 views
4

在java中,你如何知道你是否有來自Http連接的錯誤流,或者它是否是InputStream?我可以告訴做的唯一方法是兩者兼而有之,檢查null並捕獲任何異常。Java HttpConnection/HttpsConnection輸入/錯誤流

HttpConnection con = (HttpConnection)URL.openConnection(); 
    //Write to output 
    InputStream in = con.GetInputStream(); 
    //Vs 
    InputStream error = con.getErrorStream(); 

java如何確定它具有哪個流?它完全基於連接的響應代碼嗎?因此,如果其> = 200和< 300,那麼它的inputStream otherwhise它的errorStream?

謝謝。

回答

5

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 
} 
1

你可以做到這一點如下:

InputStream inStream = null; 
int responseCode = connection.getResponseCode(); 
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {    
    inStream = connection.getErrorStream();  
} 
else{ 
    inStream = connection.getInputStream(); 
} 

HTTP返回代碼意味着什麼樣的流讀回。

+0

我認爲它必須與響應代碼,但我不太確定。謝謝。 – Rcunn87 2012-02-27 20:35:54

+0

user384706的回答不處理所有情況。 HTTP_INTERNAL_ERROR(500)不是唯一可以創建錯誤流的響應代碼。而且,當響應代碼是4xx或5xx時,HttpURLConnection喜歡拋出異常。查看我的答案瞭解更多詳情。 – 2012-02-27 20:58:03

+0

我只是注意到,因爲我正在更多地研究它。 – Rcunn87 2012-02-27 21:17:59