Browsermob配置及使用

Browsermob用来抓取webDriver的请求和返回

Browsermob 的配置及使用

正常的使用

1
2
3
4
5
BrowserMobProxyServer browserMobProxy = new BrowserMobProxyServer();
InetSocketAddress chainedProxy = new InetSocketAddress(proxyIp, proxyPort);
browserMobProxy.setChainedProxy(chainedProxy);
browserMobProxy.setTrustAllServers(true);
browserMobProxy.start();

添加Filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
browserMobProxy.addLastHttpFilterFactory(new ResponseFilterAdapter.FilterSource(new ResponseFilter() {
@Override
public void filterResponse(HttpResponse response, HttpMessageContents contents, HttpMessageInfo messageInfo) {
byte[] contentsBytes = contents.getBinaryContents();
String resultString = new String(contentsBytes);
logger.info("geetest-接收到[{}]的请求结果", messageInfo.getUrl());
for (String watchUrl : watchingUrlList) {
if (messageInfo.getUrl().contains(watchUrl)) {
responseCacheMap.put(messageInfo.getUrl(), contentsBytes);
}
}
}
}, 209715200));

browserMobProxy.addRequestFilter(new RequestFilter() {
@Override
public HttpResponse filterRequest(HttpRequest request, HttpMessageContents contents, HttpMessageInfo messageInfo) {
for (Map.Entry<String, byte[]> entry : RequestCache.requestCacheMap.entrySet()) {
String url = entry.getKey();
if (messageInfo.getOriginalUrl().contains(url)) {
byte[] value = entry.getValue();
if (value != null)
// 如果有保存的请求内容,直接返回去
HttpResponse injectResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(value));
// 这里一定要返回一个header,否则浏览器会一直保持连接,导致其他的请求在等待
injectResponse.headers().add(HttpHeaderNames.CONNECTION, "Close");
return injectResponse;
}
}
}
return null;
}
});


// 以下域名作为黑名单返回404
String[] arr = new String[]{"google.com", "google.cn", "googleapis.com", "gvt1.com"};
Collection<BlacklistEntry> blackList = new ArrayList<>();
for (String s : arr) {
BlacklistEntry entry = new BlacklistEntry("^https://.*" + s + ".com/.*", 404);
blackList.add(entry);
BlacklistEntry entry2 = new BlacklistEntry("^http://.*" + s + ".com/.*", 404);
blackList.add(entry2);
}
browserMobProxy.setBlacklist(blackList);
-------------本文结束  感谢您的阅读-------------
下次一定