gpt4 book ai didi

java - 在HttpURLConnection中getErrorStream返回的InputStream中获取服务器发送来的有用数据

转载 作者:行者123 更新时间:2023-12-01 14:43:30 27 4
gpt4 key购买 nike

当我在 HttpURLConnection 中调用 getInputStream() 方法时,它返回一个 HTTP 异常,我使用此策略来捕获该异常。

try {
con.getInputStream();
} catch (IOException e) {
resStream = con.getErrorStream();
}

但是,我需要获取服务器发送到 resStream 的有用数据,如 JavaDoc 所示,如下所示。“如果连接失败但服务器仍然发送了有用的数据,则返回错误流。”

有没有办法从getErrorStream()返回的InputStream中获取响应消息(如果返回值不为null且有有效响应)?

最佳答案

您可以将此字节流包装为字符流并仅读取错误信息。

InputStreamReader isr = new InputStreamReader(resStream);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
String line = null;
while((line = buf.readLine()) != null) {
buf.append(line);
}
//assume you have a log object, you'd better not use System.out.println()
log.error(buf.toString());
//do not forget to close all the stream

然后,您可以从服务器端获取堆栈跟踪。我希望这会有所帮助。

关于java - 在HttpURLConnection中getErrorStream返回的InputStream中获取服务器发送来的有用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15699145/

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