在Java中,当HTTP结果为404范围时,此代码将引发异常:
URL url = new URL("http://stackoverflow.com/asdf404notfound"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.getInputStream(); // throws!
就我而言,我碰巧知道内容是404,但无论如何我还是想阅读响应的内容。
(在我的实际情况下,响应代码为403,但是响应的主体说明了拒绝的原因,我希望向用户显示该原因。)
如何访问响应正文?
这是错误报告(关闭,无法修复,不是错误)。
他们的建议是这样编码:
HttpURLConnection httpConn = (HttpURLConnection)_urlConnection; InputStream _is; if (httpConn.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) { _is = httpConn.getInputStream(); } else { /* error from server */ _is = httpConn.getErrorStream(); }