8

How is it possible (if at all) to get the HTTP status code from a java.io.IOException in java ?

6
  • 1
    What status code are you talking about? Are you talking about some IOException subclass that contains a status code? Commented May 18, 2016 at 14:32
  • language? example? Commented May 18, 2016 at 14:32
  • Language is written in the tags: Java Commented May 18, 2016 at 14:35
  • Please provide an example. Commented May 18, 2016 at 14:35
  • I see no mention whatsoever of a status code in java.io.Exception. Commented May 18, 2016 at 14:36

1 Answer 1

11

I'm assuming this is about an IOException thrown by a URLConnection.

Three possibilities to handle this, depending on your restrictions.

1) Cast your URLConnection to a HttpURLConnection and call getResponseCode

If you have access to the connection object, you can get the status code using this code:

int statusCode = (HttpURLConnection)theConnection).getResponseCode();

2) Use a HttpURLConnection instead of an URLConnection in the first place

If you can do this, it would be the best solution, because an URLConnection doesn't throw on error status codes. You can just call getResponseCode and check the status without getting any exception first.

3) Parse the exception message itself

The IOException's message usually looks like this:

Server returned HTTP response code: 403 for URL: http://something

So you can just use a regex (or simple string manipulation) to get the response code out of there.

Note that for status 404, the message doesn't look like this and a FileNotFoundException is thrown. I'm not sure if there are any other status codes throwing "special" exceptions like this, but watch out for this.

Example code demonstrating methods 2 & 3:

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class HelloWorld {
    public static void testUrl(String urlString) throws MalformedURLException {
        URLConnection conn = null;
        System.out.println("Testing URL " + urlString);
        try {
            URL url = new URL(urlString);
            conn = url.openConnection();

            // Just to make the exception happen
            conn.getInputStream();

            System.out.println("Success!");
        } catch(IOException ex) {
            System.out.println("Error!");
            System.out.println();

            // Method 2 with access to the URLConnection object
            // (Method 1 would have been having the connection as HttpURLConnection from the beginning.)
            int responseCode = 0;
            System.out.println("Trying method 2 to get status code");

            try {
                if(conn != null) {
                    // Casting to HttpURLConnection allows calling getResponseCode
                    responseCode = ((HttpURLConnection)conn).getResponseCode();
                } else {
                    System.out.println("conn variable not set");
                }
            } catch(IOException ex2) {
                System.out.println("getResponseCode threw: " + ex2);
            }

            System.out.println("Status code from calling getResponseCode: " + responseCode);
            System.out.println();

            // Method 3 without access to the URLConnection object
            responseCode = 0;
            System.out.println("Trying method 3 to get status code");

            // First we try parsing the exception message to see if it contains the response code
            Matcher exMsgStatusCodeMatcher = Pattern.compile("^Server returned HTTP response code: (\\d+)").matcher(ex.getMessage());
            if(exMsgStatusCodeMatcher.find()) {
                responseCode = Integer.parseInt(exMsgStatusCodeMatcher.group(1));
            } else if(ex.getClass().getSimpleName().equals("FileNotFoundException")) {
                // 404 is a special case because it will throw a FileNotFoundException instead of having "404" in the message
                System.out.println("Got a FileNotFoundException");
                responseCode = 404;
            } else {
                // There can be other types of exceptions not handled here
                System.out.println("Exception (" + ex.getClass().getSimpleName() + ") doesn't contain status code: " + ex);
            }

            System.out.println("Status code from parsing exception message: " + responseCode);
            System.out.println();
        }

        System.out.println("-------");
        System.out.println();
    }

    public static void main(String []args) throws MalformedURLException {
        testUrl("https://httpbin.org/status/200");
        testUrl("https://httpbin.org/status/404");
        testUrl("https://httpbin.org/status/403");
        testUrl("http://nonexistingsite1111111.com");
    }
}

Output of the example code:

Testing URL https://httpbin.org/status/200                                                                                                                                                                                        
Success!                                                                                                                                                                                                                          
-------                                                                                                                                                                                                                           

Testing URL https://httpbin.org/status/404                                                                                                                                                                                        
Error!                                                                                                                                                                                                                            

Trying method 2 to get status code                                                                                                                                                                                                
Status code from calling getResponseCode: 404                                                                                                                                                                                     

Trying method 3 to get status code                                                                                                                                                                                                
Got a FileNotFoundException                                                                                                                                                                                                       
Status code from parsing exception message: 404                                                                                                                                                                                   

-------

Testing URL https://httpbin.org/status/403                                                                                                                                                                                        
Error!                                                                                                                                                                                                                            

Trying method 2 to get status code                                                                                                                                                                                                
Status code from calling getResponseCode: 403                                                                                                                                                                                     

Trying method 3 to get status code                                                                                                                                                                                                
Status code from parsing exception message: 403                                                                                                                                                                                   

-------

Testing URL http://nonexistingsite1111111.com                                                                                                                                                                                     
Error!                                                                                                                                                                                                                            

Trying method 2 to get status code                                                                                                                                                                                                
getResponseCode threw: java.net.UnknownHostException: nonexistingsite1111111.com                                                                                                                                                  
Status code from calling getResponseCode: 0                                                                                                                                                                                       

Trying method 3 to get status code                                                                                                                                                                                                
Exception (UnknownHostException) doesn't contain status code: java.net.UnknownHostException: nonexistingsite1111111.com                                                                                                           
Status code from parsing exception message: 0                                                                                                                                                                                     

-------                                                                                                                                                                                                                           
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain how "You can just call getResponseCode and check the status without getting any exception first." applies to option 2 but not option 1? If you can cast the URLConnection to an HttpURLConnection, then it was an HttpURLConnection "in the first place" and the fact that it's been delivered to you as a URLConnection doesn't change that?
It applies to both - read my option 1 again ;) I just meant that you can either create it as HttpURLConnection in the first place or cast it to one later. In both cases, you can call getResponseCode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.