Search code examples
jsonhttpharbrowsermob-proxy

Rewrite HAR content via BrowserMobProxy and Selenium


Is it possible to change the har (with json in it) response from an https site? I see the initial json by getText(), then use setText(), and change its size by setSize and setBodySize. The content is changed as I see in debug. But it seems that there is no effect and chrome receives the same old json. Is there a way?

    public static class ResponseModifier implements ResponseInterceptor {

    @Override
    public void process(BrowserMobHttpResponse response, Har har) {

        String contentType = response.getHeader("Content-Type");

        if (contentType!=null && contentType.startsWith("application/json")){
            response.getEntry().getResponse().getContent().setText(respond);
            response.getEntry().getResponse().getContent().setSize(respond.length());
            response.getEntry().getResponse().setBodySize(respond.length());
            response.getRawResponse().removeHeaders("Content-Length");
            response.getRawResponse().addHeader("Content-Length", ""+respond.length());
        }
    }

I think maybe the point is that response.getRawResponse().getEntity().getContentLength() somehow has the old value, but I can't rewrite it. Or is the cause different?


Solution

  • It turn out to be far easier than I thought. I have to use core-littleproxy version of BMP, BrowserMobProxy class and create an instance of BrowserMobProxyServer. The I just use filter:

     proxy.addResponseFilter((response, contents, messageInfo) -> {
            if ((contents.getContentType().startsWith("application/json"))) {
                contents.setTextContents(respond);
            }
        }); 
    

    Thanks for reading :)