2

如果 getResponseCode() == 404 并因此 getInputStream() 会抛出异常,有没有办法读取如下所示的简单 http-get 的响应?如果可能的话,我更愿意继续使用 java.net。

HttpURLConnection c = (HttpURLConnection)new URL("http://somesite.com").openConnection;
c.openInputStream();

问题是,我(确实)有一个我想用 java 读取的站点,它以 404 响应,但显示在浏览器中,因为它显然会产生响应。

4

1 回答 1

4

如果. _ getErrorStream()_getResponseCode() == 404

HttpURLConnection c = (HttpURLConnection)new URL("http://somesite.com").openConnection();
InputStream in = null;
if (c.getResponseCode() >= 400) {
   in = c.getErrorStream();
}  
else {
   in = c.getInputStream();
}
于 2012-08-13T18:12:59.040 回答