0

I read from a URL type in Java and get the output line by line. But if the page didn't exist, it throws a 404 error code.

How can I add a check if the response code is 200 (and not 404), get the line? And if it is 404, print something.

    url = new URL("http://my.address.com/getfile/12345.txt");
    
    Scanner s = new Scanner(url.openStream());
    while (s.hasNextLine()) {
        s.nextLine();
        break;
    }
Tina J
  • 4,983
  • 13
  • 59
  • 125

1 Answers1

0
       try {
        URL url = new URL("https://www.google.com/");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int code = connection.getResponseCode();
        
        if (code == HttpURLConnection.HTTP_OK) {// status 200
            Scanner s = new Scanner(url.openStream());
        while (s.hasNextLine()) {
            s.nextLine();
            break;
        } 
        }else if(code == HttpURLConnection.HTTP_NOT_FOUND){//status 404
            
            // TODO: url not found 
        }else{
            // TODO: other reponse status 
        }

       
    } 
    catch (IOException ex) {
        Logger.getLogger(Week8.class.getName()).log(Level.SEVERE, null, ex);
    }

This is sample code for your scenario. I used google site for URL.

asmalindi
  • 49
  • 8