简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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