如何从HtmlUnit WebClient调用getPage并让setTimeout不要永远等待?

时间:2012-01-31 15:01:25

标签: settimeout htmlunit

我遇到与问题Call getPage from htmlunit WebClient with JavaScript disabled and setTimeout set to 10000 waits forever中描述的问题相同的问题。

那里只有一个相关(复杂)可能的答案(by theytoo)。所以我想知道是否:

  1. 有人有更简单的答案吗?
  2. 有人可以验证解决方案有效吗?

1 个答案:

答案 0 :(得分:3)

我使用的代码:

package main;

import java.io.IOException;
import java.net.MalformedURLException;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;

public class Test {

    public static void main(final String[] args) {
        final WebClient webClient = new WebClient();
        webClient.setTimeout(1000);
        try {
            System.out.println("Querying");
            webClient.getPage("http://www.google.com");
            System.out.println("Success");
        } catch (final FailingHttpStatusCodeException e) {
            System.out.println("One");
            e.printStackTrace();
        } catch (final MalformedURLException e) {
            System.out.println("Two");
            e.printStackTrace();
        } catch (final IOException e) {
            System.out.println("Three");
            e.printStackTrace();
        } catch (final Exception e) {
            System.out.println("Four");
            e.printStackTrace();
        }
        System.out.println("Finished");
    }

}

输出(删除所有CSS和JS警告):

Querying
Success
Finished

将超时从1000更改为1(我在不到1毫秒内赢得了谷歌):

Querying
Three
org.apache.http.conn.ConnectTimeoutException: Connect to www.google.com:80 timed out
    at com.gargoylesoftware.htmlunit.SocksSocketFactory.connectSocket(SocksSocketFactory.java:92)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:776)
    at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:152)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1439)
    at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1358)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:307)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:373)
    at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:358)
    at main.Test.main(Test.java:17)
Finished

结论:我无法重现它并且按预期工作