[英]Java HttpConnection/HttpsConnection input/error stream
在java中你怎么知道你是否有來自Http(s)連接的錯誤流或者它是否是一個InputStream? 我可以告訴它做的唯一方法是同時使用,檢查null並捕獲任何異常。
HttpConnection con = (HttpConnection)URL.openConnection();
//Write to output
InputStream in = con.GetInputStream();
//Vs
InputStream error = con.getErrorStream();
java如何確定它具有哪個流? 它僅僅基於連接的響應代碼嗎? 所以,如果它> = 200且<300那么它的inputStream以外是一個errorStream嗎?
謝謝。
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
}
你可以這樣做:
InputStream inStream = null;
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
inStream = connection.getErrorStream();
}
else{
inStream = connection.getInputStream();
}
HTTP
返回代碼表示要回讀的流的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.