首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Java中读取错误响应主体

在Java中,读取错误响应主体可以通过以下方法实现:

  1. 使用HttpURLConnection类发送HTTP请求,并在请求失败时读取错误响应主体。
代码语言:java
复制
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();
        }
    }
}
  1. 使用java.net.HttpURLConnection类的getErrorStream()方法获取错误响应主体,并使用java.io.BufferedReader类读取错误响应主体。
代码语言:java
复制
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类读取错误响应主体。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券