Search code examples
htmlunit

setUserAgent no longer avialble in HtmlUnit 2.28?


The code below works fine in HtmlUnit 2.27, but the setUserAgent method is not available in 2.28 what is the correct way of setting the useragent now?

BrowserVersion bv = BrowserVersion.CHROME;
bv.setUserAgent(
        "Mozilla/5.0 (Linux; Android 6.0; XT1063 Build/MPBS24.65-34-4; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36");

Solution

  • Starting with 2.28 it is no longer possible to modify the build in browser versions. There are various reasons for this and we had some discussions about possible fixes on our mailing lists.

    In the end we are using a factory pattern to setup new browser configurations and make them unchangeable afterwards.

    final BrowserVersionBuilder myChromeBuilder = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.CHROME);
    // do your setup here
    myChromeBuilder.setXXX(..);
    final BrowserVersion myChrome = myChromeBuilder.build();
    

    If you like you can also use a more fluent style for the code

    final BrowserVersion myChrome = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.CHROME)
        // do your setup here
        .setXXX(..)
        .build();