javaioexception

FileNotFoundException for URL that works in browser


I am trying to use an API from https://us.mc-api.net/ for a project and I have made this as a test.

public static void main(String[] args){
     try {
         URL url = new URL("http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/");
          BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
          String line;
          while ((line = in.readLine()) != null) {
                System.out.println(line);
                }
          in.close();  
                 }
                    catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("I/O Error");

                    }
                }
}

And this is giving me an IOException error but when ever I open the same page in my web browser I get

false,Unknown-Username

which is what I want to get from the code. I am new and don't really know why it is happening or why. EDIT: StackTrace

java.io.FileNotFoundException: http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at com.theman1928.Test.Main.main(Main.java:13)

Solution

  • The URL is returning status code 404 and therefore the input stream (mild guess here) is not being created and therefore is null. Sort the status code and you should be OK.

    Ran it with this CSV and it is fine: other csv

    If the error code is important to you then you can use HttpURLConnection:

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        System.out.println("code:"+conn.getResponseCode());
    

    In that way you can process the response code before proceeding with a quick if-then-else check.