-1

我的此代码适用于 Java6,但不适用于 Java7。我同时使用了 HtmlUnit2.12 和 HtmlUnit2.17,没有任何效果。请建议我在这里缺少什么?

从 Java7 我得到这个异常: java.net.SocketTimeoutException: Read timed out

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

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class Test {
    public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
        String url = "http : / / kellyserviceshk . force . com / careers";
        String content = fetchPage(url, "firefox", 30000, true);
        System.out.println(content);
    }

    private static String fetchPage(String url, String browser, long delayinmillis, boolean javaScriptEnable) {
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_17);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setUseInsecureSSL(true);
        webClient.getCookieManager().setCookiesEnabled(true);
        webClient.getOptions().setJavaScriptEnabled(javaScriptEnable);
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());

        String content="";
        try {               
            HtmlPage page = webClient.getPage(url);
            webClient.waitForBackgroundJavaScript(delayinmillis);
            content = page.asXml();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(webClient!=null){
                webClient.closeAllWindows();
                webClient=null;
            }

        }
        return content;
    }

}

在更改 HtmlUnit2.17 时,我使用 BrowserVersion 作为 FIREFOX_38,而不是 FIREFOX_17。我应该做出哪些改变?

4

1 回答 1

1

您可以尝试定义超时:

webClient.getOptions().setTimeout(0); // zero for an infinite wait. (time in milliseconds)

默认超时为 90 秒(在 HtmlUnit-2.11 之前为 0)。

于 2015-06-18T08:41:27.317 回答