Java URL检查404 HTTP响应代码

问题描述

我从Java中的main()类型读取并逐行获取输出。但是,如果该页面不存在,则会抛出一个URL错误代码

如何添加响应代码是否为404(而不是200)的检查?如果是404,请打印一些内容

404

解决方法

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

这是您的方案的示例代码。我使用Google网站作为URL。