阅读回复即使它是404

时间:2012-08-13 18:07:45

标签: java http-status-code-404

有没有办法读取如下所示的简单http-get的响应,如果getResponseCode()== 404,那么getInputStream()会抛出异常?如果可能的话,我宁愿留在java.net。

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

事情是,我确实有一个我想用java读取的网站用404响应,但是在浏览器中显示,因为它显然反过来讽刺。

1 个答案:

答案 0 :(得分:3)

如果getResponseCode() == 404

,您想使用getErrorStream() method
HttpURLConnection c = (HttpURLConnection)new URL("http://somesite.com").openConnection();
InputStream in = null;
if (c.getResponseCode() >= 400) {
   in = c.getErrorStream();
}  
else {
   in = c.getInputStream();
}