我们的应用程序使用了apache HttpAsyncClient的各种用法:
CloseableHttpAsyncClient client= ...
HttpGet get = new HttpGet(...);
Future<HttpResponse> f = client.execute(get,null);
HttpResponse resp=f.get()
我正在寻找一些钩子来捕获响应,就在它被传递给调用'f.get()'的业务代码之前。在这个钩子里面,我将进行审计和安全卫生。 BTW响应是短文本,因此缓冲没有问题。 有人会碰巧知道这样的钩子吗?
我尝试过HttpRequestInterceptor,但它似乎只适用于同步客户端:
// hook to audit & sanitize *synchronous* client response:
HttpClients.custom().addInterceptorLast(new HttpRequestInterceptor(){
public void process(HttpRequest req, HttpContext ctx) {
HttpEntityEnclosingRequest enclosing=(HttpEntityEnclosingRequest)req;
String body=EntityUtils.toString(enclosing.getEntity());
// ... audit 'body'
// ... sanitize 'body'
enclosing.setEntity(new StringEntity(sanitizedBody))
不幸的是,它不适用于异步客户端 - 我怀疑拦截器在响应准备就绪之前运行;我正在寻找一个在异步响应 准备就绪时运行的钩子。
由于
答案 0 :(得分:1)
考虑使用自定义HttpAsyncResponseConsumer
。这可以让您完全控制响应消息处理。
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
HttpAsyncResponseConsumer responseConsumer = new BasicAsyncResponseConsumer() {
@Override
protected void onResponseReceived(final HttpResponse response) throws IOException {
super.onResponseReceived(response);
}
@Override
protected void onEntityEnclosed(final HttpEntity entity, final ContentType contentType) throws IOException {
super.onEntityEnclosed(entity, contentType);
}
@Override
protected void onContentReceived(final ContentDecoder decoder, final IOControl ioctrl) throws IOException {
super.onContentReceived(decoder, ioctrl);
}
@Override
protected HttpResponse buildResult(HttpContext context) {
return super.buildResult(context);
}
@Override
protected void releaseResources() {
super.releaseResources();
}
};
client.execute(HttpAsyncMethods.createGet("http://target/"), consumer, null);
PS:可以通过阻止HttpClient但不能使用HttpAsyncClient访问来自协议拦截器内部的消息内容流