在Java中,读取错误响应主体可以通过以下方法实现:
HttpURLConnection
类发送HTTP请求,并在请求失败时读取错误响应主体。import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ErrorResponseReader {
public static void main(String[] args) {
try {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("Error response: " + response.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
java.net.HttpURLConnection
类的getErrorStream()
方法获取错误响应主体,并使用java.io.BufferedReader
类读取错误响应主体。import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ErrorResponseReader {
public static void main(String[] args) {
try {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("Error response: " + response.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这两个示例中,我们使用HttpURLConnection
类发送HTTP请求,并在请求失败时读取错误响应主体。我们使用getErrorStream()
方法获取错误响应主体,并使用BufferedReader
类读取错误响应主体。
领取专属 10元无门槛券
手把手带您无忧上云