gpt4 book ai didi

Java HttpConnection/HttpsConnection 输入/错误流

转载 作者:搜寻专家 更新时间:2023-11-01 02:14:28 26 4
gpt4 key购买 nike

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

关于Java HttpConnection/HttpsConnection 输入/错误流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9471568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com