Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果服务器返回502错误,如何读取HTTP响应?_Java_Http_Post_Request_Response - Fatal编程技术网

Java 如果服务器返回502错误,如何读取HTTP响应?

Java 如果服务器返回502错误,如何读取HTTP响应?,java,http,post,request,response,Java,Http,Post,Request,Response,我使用URLConnection向服务器发送POST请求,并使用以下代码读取响应: String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { response += line; } reader.close(); 但是,服务器有时会返回一个502

我使用
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>
服务器为URL返回了HTTP响应代码:502:

如何绕过此问题?

根据这些行修改代码,以便获得errorstream而不是抛出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();

沿着这些行修改代码,以便获得errorstream,而不是抛出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();