1

我正在创建一个教育终端应用程序,它通过URL.openStream(). 根据查询,页面可能会返回 500 错误代码。但是,我想在正文中显示一个有价值的错误描述。

不幸URL.openStream()的是,遇到返回码 500 时会抛出 IOException,一旦捕获到异常,我就无法读取流。

BufferedReader in = null;
try {
  URL url_connection = new URL(url);
  in = new BufferedReader(new InputStreamReader(url_connection.openStream()));
} catch (IOException e) {
}

该变量in将保持为空,因为在 openStream 返回之前引发了异常。

如何从 HTTP 响应中读取 HTML 代码?

4

1 回答 1

2

I found a solution by using HttpURLConnection, which has a method called getErrorStream():

HttpURLConnection conn = null;
try {
  URL url_connection = new URL(url);
  conn = (HttpURLConnection) url_connection.openConnection();
  System.out.println(new String(conn.getInputStream().readAllBytes()));
} catch (IOException e) {
  System.out.println(new String(conn.getErrorStream().readAllBytes()));
}
于 2019-07-17T20:21:13.077 回答