0

我曾经URLConnection向服务器发送 POST 请求,我正在使用以下代码来读取响应:

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));   
while ((line = reader.readLine()) != null) {
    response += line;
}
reader.close();

但是,服务器有时会返回 502 错误,并在响应中包含有意义的错误消息,我想获得它。我的问题是,在这种情况下尝试创建BufferedReader将导致java.io.IOException

Server returned HTTP response code: 502 for URL: <url>

我怎样才能绕过这个?

4

1 回答 1

3

沿着这些行修改您的代码,以便您可以获得错误流而不是抛出 IOException

HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
    is = httpConn.getErrorStream();
} else {
    is = httpConn.getInputStream();
}

BufferedReader reader = new BufferedReader(new  InputStreamReader(is));   
while ((line = reader.readLine()) != null) {
     response += line;
}
reader.close();
于 2013-06-27T20:20:02.460 回答