[英]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.