2

我试图弄清楚如何检查 url 是否为 404 或是否超时的逻辑。我好像想不通!

这是我到目前为止所拥有的:

while (i < retries){
            try {
                response = Jsoup.connect(url)
                        .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
                        .timeout(10000)
                        .execute();
                success = true;
                break;
            } catch (IOException e) {
                success = false;
            }
            System.out.println("Attempt " + i + " " + url);
            i++;
        }
    }

    public int getUrlStatus(){
        if(success){
            int statusCode = response.statusCode();
            return statusCode;
        }else {
            return 404;
        }
    }

据我所知,如果页面超时,这将告诉我页面 404 不是。我该如何检查呢?

4

1 回答 1

3

连接时可以捕获SocketTimeoutException

  try {
                response = Jsoup.connect(url)
                        .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
                        .timeout(10000)
                        .execute();
                success = true;
                break;
            } catch (SocketTimeoutExceptione) {
                success = false;
            System.out.println("Timeout occured");
            }
于 2012-05-15T14:33:21.937 回答