首页 > 解决方案 > Java URL 检查 404 HTTP 响应代码

问题描述

我从URLJava 中的一个类型中读取并逐行获取输出。但是如果页面不存在,它会抛出一个404错误代码。

如何添加检查响应代码是否为200(而不是404),获取该行?如果是404,打印一些东西。

    url = new URL("http://my.address.com/getfile/12345.txt");
    
    Scanner s = new Scanner(url.openStream());
    while (s.hasNextLine()) {
        s.nextLine();
        break;
    }

标签: javahttpurljava.util.scanner

解决方案


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

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


推荐阅读