Monthly Archives: March 2014

Analyzing java.io.FileNotFoundException on HttpURLConnection

Just tried to open a HttpURLConnection, but that did not go well initially. A very unclear ” java.io.FileNotFoundException ” error was thrown.

So how to analyze why this happens? First check the response code [connection.getResponseCode()], otherwise open the connection.getErrorStream(); instead of the is = connection.getInputStream();

In my case it told me that authentication had to be done first

{"errorMessages":["The requested board cannot be viewed because it either does not exist or you do not have permission to view it."],"errors":{}}

So after adding basic authentication the error was fixed and I got the required response! Here the code:

    public static String readURLWithConnection(String urlString) throws Exception {
        HttpURLConnection connection;
        InputStream is;
        URL url = new URL(urlString);
        
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
        connection.setRequestProperty("Accept", "*/*");

        String userpass = "admin:admin";
        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        connection.setRequestProperty ("Authorization", basicAuth);

        connection.connect();
        try {
            is = connection.getInputStream();
        } catch(FileNotFoundException exception){
            log.error(exception.getMessage(), exception);
            is = connection.getErrorStream();
        }

        BufferedReader theReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder response = new StringBuilder();
        String reply;
        while ((reply = theReader.readLine()) != null) {
            response.append(reply);
        }

        return response.toString();
    }