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;
    }
0

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.