【问题标题】:HtmlUnit webpage status codeHtmlUnit 网页状态码
【发布时间】:2012-06-23 22:34:12
【问题描述】:

我正在尝试获取给定页面的网络状态。但是,当它出现 404 错误时,页面不会返回状态代码,而是会抛出错误。

int status= webClient.getPage("website").getWebResponse().getStatusCode();
System.out.println( status);

有什么想法吗?

我希望查看网站何时超时,但出于测试目的,我将所需网站的 url 格式错误,以查看是否可以看到 404。

【问题讨论】:

    标签: java http-status-code-404 htmlunit


    【解决方案1】:

    根据this

    你可以这样做:

    webclient.setThrowExceptionOnFailingStatusCode(False)
    

    ****编辑***

    这会打印出你的状态码:

     WebClient webClient = new WebClient();
     webClient.setThrowExceptionOnFailingStatusCode(false);
     int status = webClient.getPage("http://google.co.uk/ffffff").getWebResponse()
                .getStatusCode();
     System.out.println(status);
    

    打印出 404 - 你的状态码。

    【讨论】:

    • 不,我要获取网页的状态码。即使是 404 错误。
    • 更新了我的答案。除非我错过了您的要求,否则它会起作用。 404是http状态码
    • 您给出的案例有效,但是我尝试使用的特定网站由于某些奇怪的原因无法正常工作。
    • 你说它不起作用是什么意思?它会抛出什么异常?
    【解决方案2】:

    或者,您可以继续允许抛出 FailingHttpStatusCodeException (true)。然后在 catch 子句中获取错误状态码。

    ...
    int status = 0;
    Object page = null;
    try {
         page = webClient.getPage(webRequest);
         webClient.close();
         if (page instanceof UnexpectedPage) {
             status = ((UnexpectedPage) page).getWebResponse().getStatusCode();
         } else if (page instanceof HtmlPage) {
             status = ((HtmlPage) page).getWebResponse().getStatusCode();
         }
         // do something else ...
    } catch (FailingHttpStatusCodeException | IOException e) {
         if (e instanceof FailingHttpStatusCodeException) {
              status = ((FailingHttpStatusCodeException) e).getStatusCode();
         }
         // do something else ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多