Search code examples
javahtmlunitweb-client

How to get websocket in webclient of gargoylesoftware


Is Websocket supported in gargoylesoftware library? I want to get websocket object in webclient.


Solution

  • Yes, WebSocket is supported since version 2.11. However, it is always recommended to use the latest version.

    Please ensure you use BrowserVersion with recent browser, e.g. CHROME, FIREFOX_38, or INTERNET_EXPLORER_11.

    E.g.:

    try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
    

    HtmlUnit will automatically handle the JavaScript with WebSocket.

    Update:

    To intercept the requests and responses, you can use:

        new WebConnectionWrapper(webClient) {
    
            public WebResponse getResponse(WebRequest request) throws IOException {
                WebResponse response = super.getResponse(request);
                if (request.getUrl().toExternalForm().contains("my_url")) {
                    String content = response.getContentAsString("UTF-8");
    
                    //change content
    
                    WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
                            response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
                    response = new WebResponse(data, request, response.getLoadTime());
                }
                return response;
            }
        };