在 java 中请求失败时如何获取 http 响应正文?

How can I get http response body when request is failed in java?

我正在寻找一种方法来在请求以状态 400 结束时接收响应正文。 我现在正在使用 java.net 建立 http 连接。

这是我使用的代码:

InputStream response = new URL("http://localhost:8888/login?token=token").openStream();
try (Scanner scanner = new Scanner(response)) {
    String responseBody = scanner.useDelimiter("\A").next();
    System.out.println(responseBody);
}

现在,我遇到了这个错误

java.io.IOException: Server returned HTTP response code: 400 for URL

当我在浏览器中打开 url 时,它会显示一个 json 文件,表示出了什么问题,但现在,我无法在 java 中收到该响应。

试试下面的代码:

package com.abc.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String url = "http://localhost:8888/login?token=token";
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            int responseCode = connection.getResponseCode();
            InputStream inputStream;
            if (200 <= responseCode && responseCode <= 299) {
                inputStream = connection.getInputStream();
            } else {
                inputStream = connection.getErrorStream();
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder response = new StringBuilder();
            String currentLine;

            while ((currentLine = in.readLine()) != null) 
                response.append(currentLine);

            System.out.println(response.toString());
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }

}

我改变了我的方法,现在它起作用了。

URL obj = new URL("http://localhost:8888/login?token=token");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);

System.out.println("Status Code : " + con.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getErrorStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();
System.out.println("Response Body:");
System.out.println(response.toString());