异步 http 客户端 - 钩子捕获响应?

asyc http client - hook to capture response?

我们的应用程序使用了 apache HttpAsyncClient 的各种用法:

CloseableHttpAsyncClient client= ...
HttpGet get = new HttpGet(...);
Future<HttpResponse> f = client.execute(get,null);
HttpResponse resp=f.get()

我正在寻找一些 钩子来捕获响应 就在它传递给调用 'f.get()' 的业务代码之前。在这个钩子中,我将执行审计和安全卫生。顺便说一句,响应是短文本,因此缓冲没有问题。 有人会碰巧知道这样的钩子吗?

我尝试了 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))

不幸的是,它不适用于异步客户端——我怀疑拦截器在响应准备好之前运行;我正在寻找一个在异步响应准备就绪时运行的挂钩。

谢谢

考虑使用自定义 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