Setting a cookie using JavaFX’s WebEngine/WebView

I have managed to solve this issue with the help of Vasiliy Baranov from Oracle. Vasiliy wrote to me:

Try putting the cookie into java.net.CookieHandler.getDefault() after
the WebView is instantiated for the first time and before the call to
WebEngine.load, e.g. as follows:

WebView webView = new WebView();
URI uri = URI.create("http://mysite.com");
Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>();
headers.put("Set-Cookie", Arrays.asList("name=value"));
java.net.CookieHandler.getDefault().put(uri, headers);
webView.getEngine().load("http://mysite.com");

This will place the cookie into the store permanently, it should be sent out on every subsequent request (presumably provided that the server doesn’t unset it).

Vasiliy also explained that WebView will install it’s own implementation of the CookieHandler, while retaining cookies put into the default one.

Lastly, he mentions something quite intriguing:

Do not waste your time trying to use java.net.CookieManager, and
java.net.CookieStore. They are likely to cause problems with many
sites because they implement the wrong standard.

I tried googling after this but it doesn’t seem to be common knowledge. If anyone is able to provide more details I would be grateful. It seems weird, since it seems CookieStore and CookieManager are used by a lot of software out there.

Leave a Comment