Java HttpConnection / HttpsConnection输入/错误流

时间:2012-02-27 20:10:32

标签: java

在java中你怎么知道你是否有来自Http(s)连接的错误流,或者它是否是一个InputStream?我可以告诉它做的唯一方法是同时使用,检查null并捕获任何异常。

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

java如何确定它拥有哪个流?它仅仅基于连接的响应代码吗?因此,如果它的&gt; = 200且<300,那么它的inputStream以及其它的错误流是什么?

感谢。

2 个答案:

答案 0 :(得分: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()可能会抛出异常。因此,在connection之后立即检查500(HTTP_INTERNAL_ERROR)可能实际上是无法访问的代码,具体取决于您访问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}}

答案 1 :(得分:1)

您可以按照以下方式执行此操作:

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

HTTP返回代码表示要回读的流的类型。