正常的网络链接的,客户端对于服务端的链接的接收为:
getInputStream();
而对于非正常链接的,如果服务端有向客户端发送内容,则其解析方式为:
getErrorStream();
但是,以上两个stream的返回都有可能为空。
From the java documentation on getErrorStream():
Returns the error stream if the connection failed but the server sent useful data nonetheless. The typical example is when an HTTP server responds with a 404, which will cause a FileNotFoundException to be thrown in connect, but the server sent an HTML help page with suggestions as to what to do. This method will not cause a connection to be initiated. If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, this method will return null. This is the default.
以下为正确的解析方式,注意,使用的是HttpURLConnection.HTTP_OK InputStream is = null; int responseCode = urlConnection.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK){ is = urlConnection.getInputStream(); }else{ is = urlConnection.getErrorStream(); }