问题
I am trying to listen to websocket messages on a particular page.
It seems like HtmlUnit has support for WebSockets, but I can't find any documentation/tutorial or even an answer to: "is it possible to intercept websocket data with htmlUnit"?
What I already tried:
try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
final HtmlPage page = webClient.getPage("url");
webClient.waitForBackgroundJavaScript(10 * 60 * 1000);
}
I get an INFO message about the websocket connection and this error:
INFO: Opening transport: xhr-streaming url:https://stream71.forexpros.com:443/echo/340/3exyl8ko RTO:357
Mar 23, 2017 5:40:07 PM com.gargoylesoftware.htmlunit.HttpWebConnection downloadContent
WARNING: Connection was closed while reading from stream.
回答1:
As of now, WebSocket
is supported only from the the JavaScript side by this class, and there is no API from HtmlUnit to control it.
The current implementation is basic, I will see if there is a way to intercept the traffic from Jetty Websocket client, it can be added to the public API.
Update:
WebClient now has getInternals().addListener()
. Once the listener.created(WebSocket)
is called, you should invoke webSocket.setWebSocketListener()
with the WebSocketListener
.
Test case is here.
This feature is included in the latest build.
来源:https://stackoverflow.com/questions/42982495/java-listen-to-websocket-messages-with-htmlunit