Search code examples
javahttphttpurlconnectionhttp-status-codes

Force java.net.HttpUrlConnection to return GET-response regardless of Http-Status-Code


I'm working on a HTTP-Client to sent GET-Requests to an API, which responds with proper JSON-Objects even when the HTTP-Status Codes contains an Error such as 401.

public String get(String url){
        URL target;
        HttpURLConnection connection;
        int code = 200;
        BufferedReader reader;
        String inputLine;
        String result = null; 

        try {
            target = new URL(url);
        } catch (MalformedURLException ex) {
            return result;
        }

        try {
            connection = (HttpURLConnection)target.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            //code = connection.getResponseCode();
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            result = "";
            while ((inputLine = reader.readLine()) != null){ 
                result += inputLine;
            }
            reader.close();
        } catch (IOException ex) {
            return "...";
        }

        return result;
}

When that's the case, the IOException is thrown and the response isn't written. However, I want to receive the response regardless of the HTTP-Status-Code and hande error handling myself. How can I achieve this?


Solution

  • I don't believe you can do that, but there's https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream-- for getting the payload in case of an error.