繁体   English   中英

当 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:服务器返回 HTTP 响应代码:400 对于 ZE6B3091A8D2C4D552A4

当我在浏览器中打开 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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM