为HttpClient提供应该阻止访问的路由,主机名,IP地址列表的最简单方法是什么?
像这样(这段代码不起作用,你现在不能设置0):
HttpHost block = new HttpHost("example.com", 80);
cm.setMaxPerRoute(new HttpRoute(block), 0);
答案 0 :(得分:1)
final Set<HttpHost> sitesToBlock = new HashSet<HttpHost>();
sitesToBlock.add(new HttpHost("example.com", 80));
DefaultRoutePlanner routePlanner = new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE) {
@Override
public HttpRoute determineRoute(
final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException {
final HttpRoute route = super.determineRoute(host, request, context);
if (sitesToBlock.contains(route.getTargetHost())) {
throw new HttpException("Connection to " + host + " is blocked");
}
return route;
}
};
CloseableHttpClient client = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
}