Class WebClient
- All Implemented Interfaces:
Serializable,AutoCloseable
A standard usage of HtmlUnit will start with using the getPage(String) method
(or getPage(URL)) to load a first Page
and will continue with further processing on this page depending on its type.
final WebClient webClient = new WebClient();
final HtmlPage startPage = webClient.getPage("http://htmlunit.sf.net");
assertEquals("HtmlUnit - Welcome to HtmlUnit", startPage.getTitleText());
Note: a WebClient instance is not thread safe. It is intended to be used from a single thread.
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classThis is a poolable CSS3Parser which can be reused automatically when closed. -
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionCreates a web client instance using the browser version returned byBrowserVersion.getDefault().WebClient(BrowserVersion browserVersion) Creates a web client instance using the specifiedBrowserVersion.WebClient(BrowserVersion browserVersion, boolean javaScriptEngineEnabled, String proxyHost, int proxyPort) Creates an instance that will use the specifiedBrowserVersionand proxy server.WebClient(BrowserVersion browserVersion, boolean javaScriptEngineEnabled, String proxyHost, int proxyPort, String proxyScheme) Creates an instance that will use the specifiedBrowserVersionand proxy server.WebClient(BrowserVersion browserVersion, String proxyHost, int proxyPort) Creates an instance that will use the specifiedBrowserVersionand proxy server.WebClient(BrowserVersion browserVersion, String proxyHost, int proxyPort, String proxyScheme) Creates an instance that will use the specifiedBrowserVersionand proxy server. -
Method Summary
Modifier and TypeMethodDescriptionvoidParses the given cookie and adds this to our cookie store.voidaddRequestHeader(String name, String value) Adds a header which will be sent with EVERY request from this client.voidaddWebWindowListener(WebWindowListener listener) Adds a listener forWebWindowEvents.voidclose()Closes all opened windows, stopping all background JavaScript processing.booleancontainsWebWindow(WebWindow webWindow) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Returns true if the list of WebWindows contains the provided one.voidderegisterWebWindow(WebWindow webWindow) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Removes a window from the list of available windows.voiddownload(WebWindow requestingWindow, String target, WebRequest request, boolean checkHash, boolean forceLoad, String forceAttachmentWithFilename, String description) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Perform the downloads and stores it for loading later into a window.static URLExpands a relative URL relative to the specified base.Gets the current AJAX controller.Returns the alert handler for this webclient.Returns the current attachment handler.Returns the current browser version.getCache()Gets the cache currently being used.Returns the current clipboard handler.Returns the confirm handler.Returns the cookie manager used by this web client.getCookies(URL url) Returns the currently configured cookies applicable to the specified URL, in an unmodifiable set.org.apache.http.client.CredentialsProviderReturns the credentials provider for this client instance.INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.org.htmlunit.cssparser.parser.CSSErrorHandlerReturns the CSS error handler used by this web client when CSS problems are encountered.Returns the "current" window for this client.Returns the executor for thisWebClient.Returns the current FrameContent handler.org.htmlunit.html.parser.HTMLParserListenerGets the configured listener for messages generated by the HTML parser.Gets the current listener for encountered incorrectness (except HTML parsing messages that are handled by the HTML parser listener).org.htmlunit.javascript.AbstractJavaScriptEngine<?> This method is intended for testing only - use at your own risk.org.htmlunit.javascript.JavaScriptErrorListenerReturns the javascript error listener for thisWebClient.longReturns the number of milliseconds that a script is allowed to execute before being terminated.Returns the onbeforeunload handler for thisWebClient.Returns the options object of this WebClient.<P extends Page>
PConvenient method to build a URL and load it into the current WebWindow as it would be done bygetPage(WebWindow, WebRequest).<P extends Page>
PConvenient method to load a URL into the current top WebWindow as it would be done bygetPage(WebWindow, WebRequest).<P extends Page>
PgetPage(WebRequest request) Convenient method to load a web request into the current top WebWindow.<P extends Page>
PgetPage(WebWindow webWindow, WebRequest webRequest) Send a request to a server and return a Page that represents the response from the server.Returns the current page creator.Returns the currentPrintHandler.Returns the prompt handler.Returns the current refresh handler.Returns the script pre processor for thisWebClient.Returns the status handler for thisWebClient.Gets the holder for the different storages.Returns an immutable list of open top level windows.Returns the object that will resolve all URL requests.Returns the WebConsole.org.htmlunit.webstart.WebStartHandlerReturns the current WebStart handler.getWebWindowByName(String name) Returns the firstWebWindowthat matches the specified name.Returns an immutable list of open web windows (whether they are top level windows or not).guessContentType(File file) Tries to guess the content type of the file.
This utility could be located in a helper class but we can compare this functionality for instance with the "Helper Applications" settings of Mozilla and therefore see it as a property of the "browser".voidinitialize(WebWindow webWindow, Page page) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Initializes a new web window for JavaScript.voidinitializeEmptyWindow(WebWindow webWindow, Page page) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Initializes a new empty window for JavaScript.booleanReturns true if the javaScript support is enabled.booleanReturns true if the javaScript engine is enabled.booleanDeprecated.voidINTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Loads downloaded responses into the corresponding windows.loadHtmlCodeIntoCurrentWindow(String htmlCode) Parses the given XHtml code string and loads the resulting XHtmlPage into the current window.loadWebResponse(WebRequest webRequest) Loads aWebResponsefrom the server.loadWebResponseInto(WebResponse webResponse, WebWindow webWindow) Creates a page based on the specified response and inserts it into the specified window.loadWebResponseInto(WebResponse webResponse, WebWindow webWindow, String forceAttachmentWithFilename) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.loadXHtmlCodeIntoCurrentWindow(String xhtmlCode) Parses the given XHtml code string and loads the resulting XHtmlPage into the current window.openDialogWindow(URL url, WebWindow opener, Object dialogArguments) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.openTargetWindow(WebWindow opener, String windowName, String defaultName) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Open the window with the specified name.openWindow(URL url, String windowName) Open a new window with the specified name.openWindow(URL url, String windowName, WebWindow opener) Open a new window with the specified name.voidprintContentIfNecessary(WebResponse webResponse) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.voidregisterWebWindow(WebWindow webWindow) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Adds a new window to the list of available windows.voidremoveRequestHeader(String name) Removes a header from being sent with EVERY request from this client.voidremoveWebWindowListener(WebWindowListener listener) Removes a listener forWebWindowEvents.voidreset()Experimental API: May be changed in next release and may not yet work perfectly!voidsetAjaxController(AjaxController newValue) Sets the current AJAX controller.voidsetAlertHandler(AlertHandler alertHandler) Sets the alert handler for this webclient.voidsetAttachmentHandler(AttachmentHandler handler) Sets the attachment handler.voidSets the cache to use.voidsetClipboardHandler(ClipboardHandler handler) Sets the clipboard handler.voidsetConfirmHandler(ConfirmHandler handler) Sets the handler that will be executed when the JavaScript method Window.confirm() is called.voidsetCookieManager(CookieManager cookieManager) Sets the cookie manager used by this web client.voidsetCredentialsProvider(org.apache.http.client.CredentialsProvider credentialsProvider) Sets the credentials provider that will provide authentication information when trying to access protected information on a web server.voidsetCssErrorHandler(org.htmlunit.cssparser.parser.CSSErrorHandler cssErrorHandler) Sets the CSS error handler used by this web client when CSS problems are encountered.voidsetCurrentWindow(WebWindow window) Sets the "current" window for this client.voidsetExecutor(ExecutorService executor) Changes the ExecutorService for thisWebClient.voidSets the FrameContent handler.voidsetHTMLParserListener(org.htmlunit.html.parser.HTMLParserListener listener) Sets the listener for messages generated by the HTML parser.voidReturns the current HTML incorrectness listener.voidsetJavaScriptEngine(org.htmlunit.javascript.AbstractJavaScriptEngine<?> engine) This method is intended for testing only - use at your own risk.voidsetJavaScriptErrorListener(org.htmlunit.javascript.JavaScriptErrorListener javaScriptErrorListener) Sets the javascript error listener for thisWebClient.voidsetJavaScriptTimeout(long timeout) Sets the number of milliseconds that a script is allowed to execute before being terminated.voidsetOnbeforeunloadHandler(OnbeforeunloadHandler onbeforeunloadHandler) Sets the onbeforeunload handler for thisWebClient.voidsetPageCreator(PageCreator pageCreator) Sets the object that will be used to create pages.voidsetPrintHandler(PrintHandler handler) Sets thePrintHandlerto be used if Windoe.print() is called (Printing Spec).voidsetPromptHandler(PromptHandler handler) Sets the handler that will be executed when the JavaScript method Window.prompt() is called.voidsetRefreshHandler(RefreshHandler handler) Sets the handler to be used whenever a refresh is triggered.voidsetScriptPreProcessor(ScriptPreProcessor scriptPreProcessor) Sets the script pre processor for thisWebClient.voidsetStatusHandler(StatusHandler statusHandler) Sets the status handler for this webclient.voidsetWebConnection(WebConnection webConnection) Sets the object that will resolve all URL requests.voidsetWebStartHandler(org.htmlunit.webstart.WebStartHandler handler) Sets the WebStart handler.voidINTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.intwaitForBackgroundJavaScript(long timeoutMillis) Experimental API: May be changed in next release and may not yet work perfectly!intwaitForBackgroundJavaScriptStartingBefore(long delayMillis) Experimental API: May be changed in next release and may not yet work perfectly!
-
Field Details
-
TARGET_BLANK
target "_blank".- See Also:
-
TARGET_SELF
target "_self".- See Also:
-
-
Constructor Details
-
WebClient
public WebClient()Creates a web client instance using the browser version returned byBrowserVersion.getDefault(). -
WebClient
Creates a web client instance using the specifiedBrowserVersion.- Parameters:
browserVersion- the browser version to simulate
-
WebClient
Creates an instance that will use the specifiedBrowserVersionand proxy server.- Parameters:
browserVersion- the browser version to simulateproxyHost- the server that will act as proxy or null for no proxyproxyPort- the port to use on the proxy server
-
WebClient
public WebClient(BrowserVersion browserVersion, String proxyHost, int proxyPort, String proxyScheme) Creates an instance that will use the specifiedBrowserVersionand proxy server.- Parameters:
browserVersion- the browser version to simulateproxyHost- the server that will act as proxy or null for no proxyproxyPort- the port to use on the proxy serverproxyScheme- the scheme http/https
-
WebClient
public WebClient(BrowserVersion browserVersion, boolean javaScriptEngineEnabled, String proxyHost, int proxyPort) Creates an instance that will use the specifiedBrowserVersionand proxy server.- Parameters:
browserVersion- the browser version to simulatejavaScriptEngineEnabled- set to false if the simulated browser should not support javaScriptproxyHost- the server that will act as proxy or null for no proxyproxyPort- the port to use on the proxy server
-
WebClient
public WebClient(BrowserVersion browserVersion, boolean javaScriptEngineEnabled, String proxyHost, int proxyPort, String proxyScheme) Creates an instance that will use the specifiedBrowserVersionand proxy server.- Parameters:
browserVersion- the browser version to simulatejavaScriptEngineEnabled- set to false if the simulated browser should not support javaScriptproxyHost- the server that will act as proxy or null for no proxyproxyPort- the port to use on the proxy serverproxyScheme- the scheme http/https
-
-
Method Details
-
getWebConnection
Returns the object that will resolve all URL requests.- Returns:
- the connection that will be used
-
setWebConnection
Sets the object that will resolve all URL requests.- Parameters:
webConnection- the new web connection
-
getPage
public <P extends Page> P getPage(WebWindow webWindow, WebRequest webRequest) throws IOException, FailingHttpStatusCodeException Send a request to a server and return a Page that represents the response from the server. This page will be used to populate the provided window.The returned
Pagewill be created by thePageCreatorconfigured bysetPageCreator(PageCreator), if any.The
DefaultPageCreatorwill create aPagedepending on the content type of the HTTP response, basicallyHtmlPagefor HTML content,XmlPagefor XML content,TextPagefor other text content andUnexpectedPagefor anything else.- Type Parameters:
P- the page type- Parameters:
webWindow- the WebWindow to load the result of the request intowebRequest- the web request- Returns:
- the page returned by the server when the specified request was made in the specified window
- Throws:
IOException- if an IO error occursFailingHttpStatusCodeException- if the server returns a failing status code AND the propertyWebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)is set to true- See Also:
-
getPage
public <P extends Page> P getPage(String url) throws IOException, FailingHttpStatusCodeException, MalformedURLException Convenient method to build a URL and load it into the current WebWindow as it would be done bygetPage(WebWindow, WebRequest).- Type Parameters:
P- the page type- Parameters:
url- the URL of the new content- Returns:
- the new page
- Throws:
FailingHttpStatusCodeException- if the server returns a failing status code AND the propertyWebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)is set to true.IOException- if an IO problem occursMalformedURLException- if no URL can be created from the provided string
-
getPage
Convenient method to load a URL into the current top WebWindow as it would be done bygetPage(WebWindow, WebRequest).- Type Parameters:
P- the page type- Parameters:
url- the URL of the new content- Returns:
- the new page
- Throws:
FailingHttpStatusCodeException- if the server returns a failing status code AND the propertyWebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)is set to true.IOException- if an IO problem occurs
-
getPage
public <P extends Page> P getPage(WebRequest request) throws IOException, FailingHttpStatusCodeException Convenient method to load a web request into the current top WebWindow.- Type Parameters:
P- the page type- Parameters:
request- the request parameters- Returns:
- the new page
- Throws:
FailingHttpStatusCodeException- if the server returns a failing status code AND the propertyWebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)is set to true.IOException- if an IO problem occurs- See Also:
-
loadWebResponseInto
public Page loadWebResponseInto(WebResponse webResponse, WebWindow webWindow) throws IOException, FailingHttpStatusCodeException Creates a page based on the specified response and inserts it into the specified window. All page initialization and event notification is handled here.
Note that if the page created is an attachment page, and an
AttachmentHandlerhas been registered with this client, the page is not loaded into the specified window; in this case, the page is loaded into a new window, and attachment handling is delegated to the registeredAttachmentHandler.- Parameters:
webResponse- the response that will be used to create the new pagewebWindow- the window that the new page will be placed within- Returns:
- the newly created page
- Throws:
IOException- if an IO error occursFailingHttpStatusCodeException- if the server returns a failing status code AND the propertyWebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)is set to true- See Also:
-
loadWebResponseInto
public Page loadWebResponseInto(WebResponse webResponse, WebWindow webWindow, String forceAttachmentWithFilename) throws IOException, FailingHttpStatusCodeException INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Creates a page based on the specified response and inserts it into the specified window. All page initialization and event notification is handled here.
Note that if the page created is an attachment page, and an
AttachmentHandlerhas been registered with this client, the page is not loaded into the specified window; in this case, the page is loaded into a new window, and attachment handling is delegated to the registeredAttachmentHandler.- Parameters:
webResponse- the response that will be used to create the new pagewebWindow- the window that the new page will be placed withinforceAttachmentWithFilename- if notnull, handle this as an attachment with the specified name or if an empty string ("") use the filename provided in the response- Returns:
- the newly created page
- Throws:
IOException- if an IO error occursFailingHttpStatusCodeException- if the server returns a failing status code AND the propertyWebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)is set to true- See Also:
-
printContentIfNecessary
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.Logs the response's content if its status code indicates a request failure and
WebClientOptions.isPrintContentOnFailingStatusCode()returnstrue.- Parameters:
webResponse- the response whose content may be logged
-
throwFailingHttpStatusCodeExceptionIfNecessary
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.Throws a
FailingHttpStatusCodeExceptionif the request's status code indicates a request failure andWebClientOptions.isThrowExceptionOnFailingStatusCode()returnstrue.- Parameters:
webResponse- the response which may trigger aFailingHttpStatusCodeException
-
addRequestHeader
Adds a header which will be sent with EVERY request from this client. This list is empty per default; use this to add specific headers for your case.- Parameters:
name- the name of the header to addvalue- the value of the header to add- See Also:
-
removeRequestHeader
Removes a header from being sent with EVERY request from this client. This list is empty per default; use this method to remove specific headers your have added using {addRequestHeader(String, String)before.
You can't use this to avoid sending standard headers like "Accept-Language" or "Sec-Fetch-Dest".- Parameters:
name- the name of the header to remove- See Also:
-
setCredentialsProvider
public void setCredentialsProvider(org.apache.http.client.CredentialsProvider credentialsProvider) Sets the credentials provider that will provide authentication information when trying to access protected information on a web server. This information is required when the server is using Basic HTTP authentication, NTLM authentication, or Digest authentication.- Parameters:
credentialsProvider- the new credentials provider to use to authenticate
-
getCredentialsProvider
public org.apache.http.client.CredentialsProvider getCredentialsProvider()Returns the credentials provider for this client instance. By default, this method returns an instance ofDefaultCredentialsProvider.- Returns:
- the credentials provider for this client instance
-
getJavaScriptEngine
public org.htmlunit.javascript.AbstractJavaScriptEngine<?> getJavaScriptEngine()This method is intended for testing only - use at your own risk.- Returns:
- the current JavaScript engine (never
null)
-
setJavaScriptEngine
public void setJavaScriptEngine(org.htmlunit.javascript.AbstractJavaScriptEngine<?> engine) This method is intended for testing only - use at your own risk.- Parameters:
engine- the new script engine to use
-
getCookieManager
Returns the cookie manager used by this web client.- Returns:
- the cookie manager used by this web client
-
setCookieManager
Sets the cookie manager used by this web client.- Parameters:
cookieManager- the cookie manager used by this web client
-
setAlertHandler
Sets the alert handler for this webclient.- Parameters:
alertHandler- the new alerthandler or null if none is specified
-
getAlertHandler
Returns the alert handler for this webclient.- Returns:
- the alert handler or null if one hasn't been set
-
setConfirmHandler
Sets the handler that will be executed when the JavaScript method Window.confirm() is called.- Parameters:
handler- the new handler or null if no handler is to be used
-
getConfirmHandler
Returns the confirm handler.- Returns:
- the confirm handler or null if one hasn't been set
-
setPromptHandler
Sets the handler that will be executed when the JavaScript method Window.prompt() is called.- Parameters:
handler- the new handler or null if no handler is to be used
-
getPromptHandler
Returns the prompt handler.- Returns:
- the prompt handler or null if one hasn't been set
-
setStatusHandler
Sets the status handler for this webclient.- Parameters:
statusHandler- the new status handler or null if none is specified
-
getStatusHandler
Returns the status handler for thisWebClient.- Returns:
- the status handler or null if one hasn't been set
-
getExecutor
Returns the executor for thisWebClient.- Returns:
- the executor
-
setExecutor
Changes the ExecutorService for thisWebClient. You have to call this before the first use of the executor, otherwise an IllegalStateExceptions is thrown.- Parameters:
executor- the new Executor.
-
setJavaScriptErrorListener
public void setJavaScriptErrorListener(org.htmlunit.javascript.JavaScriptErrorListener javaScriptErrorListener) Sets the javascript error listener for thisWebClient. When setting to null, theDefaultJavaScriptErrorListeneris used.- Parameters:
javaScriptErrorListener- the new JavaScriptErrorListener or null if none is specified
-
getJavaScriptErrorListener
public org.htmlunit.javascript.JavaScriptErrorListener getJavaScriptErrorListener()Returns the javascript error listener for thisWebClient.- Returns:
- the javascript error listener or null if one hasn't been set
-
getBrowserVersion
Returns the current browser version.- Returns:
- the current browser version
-
getCurrentWindow
Returns the "current" window for this client. This window (or its top window) will be used whengetPage(...)is called without specifying a window.- Returns:
- the "current" window for this client
-
setCurrentWindow
Sets the "current" window for this client. This is the window that will be used whengetPage(...)is called without specifying a window.- Parameters:
window- the new "current" window for this client
-
addWebWindowListener
Adds a listener forWebWindowEvents. All events from all windows associated with this client will be sent to the specified listener.- Parameters:
listener- a listener
-
removeWebWindowListener
Removes a listener forWebWindowEvents.- Parameters:
listener- a listener
-
openWindow
Open a new window with the specified name. If the URL is non-null then attempt to load a page from that location and put it in the new window.- Parameters:
url- the URL to load content from or null if no content is to be loadedwindowName- the name of the new window- Returns:
- the new window
-
openWindow
Open a new window with the specified name. If the URL is non-null then attempt to load a page from that location and put it in the new window.- Parameters:
url- the URL to load content from or null if no content is to be loadedwindowName- the name of the new windowopener- the web window that is calling openWindow- Returns:
- the new window
-
openTargetWindow
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Open the window with the specified name. The name may be a special target name of _self, _parent, _top, or _blank. An empty or null name is set to the default. The special target names are relative to the opener window.- Parameters:
opener- the web window that is calling openWindowwindowName- the name of the new windowdefaultName- the default target if no name is given- Returns:
- the new window
-
openDialogWindow
public DialogWindow openDialogWindow(URL url, WebWindow opener, Object dialogArguments) throws IOException INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Opens a new dialog window.- Parameters:
url- the URL of the document to load and displayopener- the web window that is opening the dialogdialogArguments- the object to make available inside the dialog viawindow.dialogArguments- Returns:
- the new dialog window
- Throws:
IOException- if there is an IO error
-
setPageCreator
Sets the object that will be used to create pages. Set this if you want to customize the type of page that is returned for a given content type.- Parameters:
pageCreator- the new page creator
-
getPageCreator
Returns the current page creator.- Returns:
- the page creator
-
getWebWindowByName
Returns the firstWebWindowthat matches the specified name.- Parameters:
name- the name to search for- Returns:
- the
WebWindowwith the specified name - Throws:
WebWindowNotFoundException- if theWebWindowcan't be found- See Also:
-
initialize
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Initializes a new web window for JavaScript.- Parameters:
webWindow- the new WebWindowpage- the page that will become the enclosing page
-
initializeEmptyWindow
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Initializes a new empty window for JavaScript.- Parameters:
webWindow- the new WebWindowpage- the page that will become the enclosing page
-
registerWebWindow
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Adds a new window to the list of available windows.- Parameters:
webWindow- the new WebWindow
-
deregisterWebWindow
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Removes a window from the list of available windows.- Parameters:
webWindow- the window to remove
-
expandUrl
Expands a relative URL relative to the specified base. In most situations this is the same asnew URL(baseUrl, relativeUrl)but there are some cases that URL doesn't handle correctly. See RFC1808 regarding Relative Uniform Resource Locators for more information.- Parameters:
baseUrl- the base URLrelativeUrl- the relative URL- Returns:
- the expansion of the specified base and relative URLs
- Throws:
MalformedURLException- if an error occurred when creating a URL object
-
guessContentType
Tries to guess the content type of the file.
This utility could be located in a helper class but we can compare this functionality for instance with the "Helper Applications" settings of Mozilla and therefore see it as a property of the "browser".- Parameters:
file- the file- Returns:
- "application/octet-stream" if nothing could be guessed
-
loadWebResponse
Loads aWebResponsefrom the server.- Parameters:
webRequest- the request- Returns:
- the WebResponse
- Throws:
IOException- if an IO problem occurs
-
getWebWindows
Returns an immutable list of open web windows (whether they are top level windows or not). This is a snapshot; future changes are not reflected by this list.The list is ordered by age, the oldest one first.
- Returns:
- an immutable list of open web windows (whether they are top level windows or not)
- See Also:
-
containsWebWindow
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Returns true if the list of WebWindows contains the provided one. This method is there to improve the performance of some internal checks because calling getWebWindows().contains(.) creates some objects without any need.- Parameters:
webWindow- the window to check- Returns:
- true or false
-
getTopLevelWindows
Returns an immutable list of open top level windows. This is a snapshot; future changes are not reflected by this list.The list is ordered by age, the oldest one first.
- Returns:
- an immutable list of open top level windows
- See Also:
-
setRefreshHandler
Sets the handler to be used whenever a refresh is triggered. Refer to the documentation forRefreshHandlerfor more details.- Parameters:
handler- the new handler
-
getRefreshHandler
Returns the current refresh handler. The default refresh handler is aNiceRefreshHandler(2).- Returns:
- the current RefreshHandler
-
setScriptPreProcessor
Sets the script pre processor for thisWebClient.- Parameters:
scriptPreProcessor- the new preprocessor or null if none is specified
-
getScriptPreProcessor
Returns the script pre processor for thisWebClient.- Returns:
- the pre processor or null of one hasn't been set
-
setHTMLParserListener
public void setHTMLParserListener(org.htmlunit.html.parser.HTMLParserListener listener) Sets the listener for messages generated by the HTML parser.- Parameters:
listener- the new listener,nullif messages should be totally ignored
-
getHTMLParserListener
public org.htmlunit.html.parser.HTMLParserListener getHTMLParserListener()Gets the configured listener for messages generated by the HTML parser.- Returns:
nullif no listener is defined (default value)
-
getCssErrorHandler
public org.htmlunit.cssparser.parser.CSSErrorHandler getCssErrorHandler()Returns the CSS error handler used by this web client when CSS problems are encountered.- Returns:
- the CSS error handler used by this web client when CSS problems are encountered
- See Also:
-
setCssErrorHandler
public void setCssErrorHandler(org.htmlunit.cssparser.parser.CSSErrorHandler cssErrorHandler) Sets the CSS error handler used by this web client when CSS problems are encountered.- Parameters:
cssErrorHandler- the CSS error handler used by this web client when CSS problems are encountered- See Also:
-
setJavaScriptTimeout
public void setJavaScriptTimeout(long timeout) Sets the number of milliseconds that a script is allowed to execute before being terminated. A value of 0 or less means no timeout.- Parameters:
timeout- the timeout value, in milliseconds
-
getJavaScriptTimeout
public long getJavaScriptTimeout()Returns the number of milliseconds that a script is allowed to execute before being terminated. A value of 0 or less means no timeout.- Returns:
- the timeout value, in milliseconds
-
getIncorrectnessListener
Gets the current listener for encountered incorrectness (except HTML parsing messages that are handled by the HTML parser listener). Default value is an instance ofIncorrectnessListenerImpl.- Returns:
- the current listener (not
null)
-
setIncorrectnessListener
Returns the current HTML incorrectness listener.- Parameters:
listener- the new value (notnull)
-
getWebConsole
Returns the WebConsole.- Returns:
- the web console
-
getAjaxController
Gets the current AJAX controller.- Returns:
- the controller
-
setAjaxController
Sets the current AJAX controller.- Parameters:
newValue- the controller
-
setAttachmentHandler
Sets the attachment handler.- Parameters:
handler- the new attachment handler
-
getAttachmentHandler
Returns the current attachment handler.- Returns:
- the current attachment handler
-
setWebStartHandler
public void setWebStartHandler(org.htmlunit.webstart.WebStartHandler handler) Sets the WebStart handler.- Parameters:
handler- the new WebStart handler
-
getWebStartHandler
public org.htmlunit.webstart.WebStartHandler getWebStartHandler()Returns the current WebStart handler.- Returns:
- the current WebStart handler
-
getClipboardHandler
Returns the current clipboard handler.- Returns:
- the current clipboard handler
-
setClipboardHandler
Sets the clipboard handler.- Parameters:
handler- the new clipboard handler
-
getPrintHandler
Returns the currentPrintHandler.- Returns:
- the current
PrintHandleror null if print requests are ignored
-
setPrintHandler
Sets thePrintHandlerto be used if Windoe.print() is called (Printing Spec).- Parameters:
handler- the newPrintHandleror null if you like to ignore print requests (default is null)
-
getFrameContentHandler
Returns the current FrameContent handler.- Returns:
- the current FrameContent handler
-
setFrameContentHandler
Sets the FrameContent handler.- Parameters:
handler- the new FrameContent handler
-
setOnbeforeunloadHandler
Sets the onbeforeunload handler for thisWebClient.- Parameters:
onbeforeunloadHandler- the new onbeforeunloadHandler or null if none is specified
-
getOnbeforeunloadHandler
Returns the onbeforeunload handler for thisWebClient.- Returns:
- the onbeforeunload handler or null if one hasn't been set
-
getCache
Gets the cache currently being used.- Returns:
- the cache (may not be null)
-
setCache
Sets the cache to use.- Parameters:
cache- the new cache (must not benull)
-
close
public void close()Closes all opened windows, stopping all background JavaScript processing. The WebClient is not really usable after this - you have to create a new one or use WebClient.reset() instead.- Specified by:
closein interfaceAutoCloseable
-
reset
public void reset()Experimental API: May be changed in next release and may not yet work perfectly!
This shuts down the whole client and restarts with a new empty window. Cookies and other states are preserved.
-
waitForBackgroundJavaScript
public int waitForBackgroundJavaScript(long timeoutMillis) Experimental API: May be changed in next release and may not yet work perfectly!
This method blocks until all background JavaScript tasks have finished executing. Background JavaScript tasks are JavaScript tasks scheduled for execution via
window.setTimeout,window.setIntervalor asynchronousXMLHttpRequest.If a job is scheduled to begin executing after
(now + timeoutMillis), this method will wait fortimeoutMillismilliseconds and then return a value greater than0. This method will never block longer thantimeoutMillismilliseconds.Use this method instead of
waitForBackgroundJavaScriptStartingBefore(long)if you don't know when your background JavaScript is supposed to start executing, but you're fairly sure that you know how long it should take to finish executing.- Parameters:
timeoutMillis- the maximum amount of time to wait (in milliseconds)- Returns:
- the number of background JavaScript jobs still executing or waiting to be executed when this
method returns; will be
0if there are no jobs left to execute
-
waitForBackgroundJavaScriptStartingBefore
public int waitForBackgroundJavaScriptStartingBefore(long delayMillis) Experimental API: May be changed in next release and may not yet work perfectly!
This method blocks until all background JavaScript tasks scheduled to start executing before
(now + delayMillis)have finished executing. Background JavaScript tasks are JavaScript tasks scheduled for execution viawindow.setTimeout,window.setIntervalor asynchronousXMLHttpRequest.If there is no background JavaScript task currently executing, and there is no background JavaScript task scheduled to start executing within the specified time, this method returns immediately -- even if there are tasks scheduled to be executed after
(now + delayMillis).Note that the total time spent executing a background JavaScript task is never known ahead of time, so this method makes no guarantees as to how long it will block.
Use this method instead of
waitForBackgroundJavaScript(long)if you know roughly when your background JavaScript is supposed to start executing, but you're not necessarily sure how long it will take to execute.- Parameters:
delayMillis- the delay which determines the background tasks to wait for (in milliseconds)- Returns:
- the number of background JavaScript jobs still executing or waiting to be executed when this
method returns; will be
0if there are no jobs left to execute
-
download
public void download(WebWindow requestingWindow, String target, WebRequest request, boolean checkHash, boolean forceLoad, String forceAttachmentWithFilename, String description) INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Perform the downloads and stores it for loading later into a window. In the future downloads should be performed in parallel in separated threads. TODO: refactor it before next release.- Parameters:
requestingWindow- the window from which the request comestarget- the name of the target windowrequest- the request to performcheckHash- if true check for hashChenageforceLoad- if true always load the request even if there is already the same in the queueforceAttachmentWithFilename- if notnullthe AttachmentHandler isAttachment() method is not called, the response has to be handled as attachment in any casedescription- information about the origin of the request. Useful for debugging.
-
loadDownloadedResponses
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.
Loads downloaded responses into the corresponding windows. TODO: refactor it before next release.- Throws:
IOException- in case of exceptionFailingHttpStatusCodeException- in case of exception
-
getOptions
Returns the options object of this WebClient.- Returns:
- the options object
-
getStorageHolder
Gets the holder for the different storages.Experimental API: May be changed in next release!
- Returns:
- the holder
-
getCookies
Returns the currently configured cookies applicable to the specified URL, in an unmodifiable set. If disabled, this returns an empty set.- Parameters:
url- the URL on which to filter the returned cookies- Returns:
- the currently configured cookies applicable to the specified URL, in an unmodifiable set
-
addCookie
Parses the given cookie and adds this to our cookie store.- Parameters:
cookieString- the string to parsepageUrl- the url of the page that likes to set the cookieorigin- the requester
-
isJavaScriptEnabled
public boolean isJavaScriptEnabled()Returns true if the javaScript support is enabled. To disable the javascript support (eg. temporary) you have to use theWebClientOptions.setJavaScriptEnabled(boolean)setter.- Returns:
- true if the javaScript engine and the javaScript support is enabled.
- See Also:
-
isJavaScriptEngineEnabled
public boolean isJavaScriptEngineEnabled()Returns true if the javaScript engine is enabled. To disable the javascript engine you have to use theWebClient(BrowserVersion, boolean, String, int)constructor.- Returns:
- true if the javaScript engine is enabled.
-
loadHtmlCodeIntoCurrentWindow
Parses the given XHtml code string and loads the resulting XHtmlPage into the current window.- Parameters:
htmlCode- the html code as string- Returns:
- the HtmlPage
- Throws:
IOException- in case of error
-
loadXHtmlCodeIntoCurrentWindow
Parses the given XHtml code string and loads the resulting XHtmlPage into the current window.- Parameters:
xhtmlCode- the xhtml code as string- Returns:
- the XHtmlPage
- Throws:
IOException- in case of error
-
getCSS3Parser
INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.- Returns:
- a CSS3Parser that will return to an internal pool for reuse if closed using the try-with-resource concept
-
isLoadStaticContent
Deprecated.Returns whether or not download of static content is enabled.XLT-specific internal API. May be removed in next release without further notice.
This is a dummy implementation that just returns
true.- Returns:
true
-