Search code examples
javahttphttpurlconnection

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


I'm looking for a way to receive the response body when a request ends up with the status 400. I'm now using java.net to make http connection.

Here is the code I'm using:

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);
}

Right now, I end up with this error

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

When I open the url in my browser it shows me a json file representing what went wrong, but now, I can't receive that response in java.


Solution

  • Try the below code :

    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();
            }       
        }
    
    }