Browsermob Proxy(java):无法重写URL

时间:2016-05-31 14:09:16

标签: java url-rewriting browsermob-proxy

我正在使用BrowserMob Proxy,我想将流量从我的生产服务器重定向到测试服务器。为此,我以下列方式使用rewriteUrl

public class Main {

    public static void main(String[] args) {

        BrowserMobProxyServer server = new BrowserMobProxyServer();
        server.setTrustAllServers(true);

        server.start(8888);
        server.rewriteUrl("(https?://)init.mycompany.com(.*)","$1platform-sandbox.mycompany.com$2//");

        if (server.isStarted()) {
            System.out.println("Server started on " + server.getClientBindAddress() + ":" + server.getPort());
        }

        server.addRequestFilter(new RequestFilter() {
            @Override
            public HttpResponse filterRequest(io.netty.handler.codec.http.HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) {
                System.out.println("REQUEST");
                System.out.println("Original: " + httpMessageInfo.getOriginalUrl());
                System.out.println("Current: " + httpMessageInfo.getUrl());
                return null;
            }
        });

        server.addResponseFilter(new ResponseFilter() {
            @Override
            public void filterResponse(HttpResponse httpResponse, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) {
                System.out.println("RESPONSE");
                System.out.println("Original: " + httpMessageInfo.getOriginalUrl());
                System.out.println("Current: " + httpMessageInfo.getUrl());
                if (httpMessageInfo.getOriginalUrl() != httpMessageInfo.getUrl()) {
                    System.out.printf("DIFFERENT!!!!");
                }
            }
        });

        server.newHar("test");
        while (true) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

您会注意到我取得了部分成功:

  1. 最后添加了两个//符号(用于测试)。
  2. 但是,init不会被platform-sandbox
  3. 取代

    REQUEST

    原文:https://init.mycompany.com

    目前:https://init.mycompany.com

    REQUEST

    原文:https://init.mycompany.com/sdk/v6.4.6?applicationKey=42a8c1f5

    目前:https://init.mycompany.com/sdk/v6.4.6?applicationKey=42a8c1f5

    RESPONSE

    原文:https://init.mycompany.com/sdk/v6.4.6?applicationKey=42a8c1f5

    目前:https://init.mycompany.com/sdk/v6.4.6?applicationKey=42a8c1f5//

1 个答案:

答案 0 :(得分:1)

我已使用http请求测试了您的代码,但效果很好(platform-sandbox已替换为CONNECT)。

仅在https请求的情况下才会出现此问题。 请求https URL时,请求方法CONNECT用于建立隧道连接。目前,如果请求方法为CONNECT,则Browsermob Proxy不支持重写URL。

源代码中有更多详细信息。您可以在this line in the code上设置断点,并通过此点调试http和https流量以查看差异。 如果使用请求方法{{1}}时出现https流量,则RewriteUrlFilter将返回null,并且重写规则不会应用于此类请求。