package test; //www.cnblogs.com/chenying99/articles/3213544.html import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController; import com.gargoylesoftware.htmlunit.WebClient; //多線程webclient,本方案簡單、小巧,容易理解 //ThreadLocalClientFactory.getInstance().getWebClient()調用 public class ThreadLocalClientFactory{ //單例工廠模式 private final static ThreadLocalClientFactory instance =new ThreadLocalClientFactory(); public static ThreadLocalClientFactory getInstance(){ return instance; } // 覆寫ThreadLocal的initialValue方法 //線程的本地實例存儲器,用於存儲WebClient實例 private ThreadLocal<WebClient> client = new ThreadLocal<WebClient>() { @Override //該方法ThreadLocal變量第一次get的時候執行,若是該線程已經執行過set方法,initialValue不會執行 protected synchronized WebClient initialValue(){ WebClient webClient = new WebClient(BrowserVersion.FIREFOX_17); //設置webClient的相關參數 webClient.getCookieManager().setCookiesEnabled(true);// 開啓cookie管理 webClient.getOptions().setJavaScriptEnabled(true);// 開啓js解析 webClient.getOptions().setCssEnabled(false); // 當出現Http error時,程序不拋異常繼續執行 webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); // 防止js語法錯誤拋出異常 webClient.getOptions().setThrowExceptionOnScriptError(false); // js運行錯誤時,是否拋出異常 webClient.getOptions().setTimeout(10000); // 默認是false, 設置爲true的話不讓你的瀏覽行爲被記錄 webClient.getOptions().setDoNotTrackEnabled(false); // 設置Ajax異步處理控制器即啓用Ajax支持 webClient .setAjaxController(new NicelyResynchronizingAjaxController()); return webClient; } }; public void setWebClient(WebClient wc) { client.set(wc); } public WebClient getWebClient() { return client.get(); } }