java - asyc http 客户端 - Hook 来捕获响应?

标签 java apache-httpclient-4.x

我们的应用程序对 apache HttpAsyncClient 进行了各种使用:

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

我正在寻找一些钩子(Hook)来捕获响应,然后将其传递给调用 'f.get()' 的业务代码。在这个钩子(Hook)中,我将执行审核和安全清理。顺便说一句,响应是短文本,因此缓冲没有问题。 请问有人知道这样的钩子(Hook)吗?

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

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

谢谢

最佳答案

考虑使用自定义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 从协议(protocol)拦截器内部访问消息内容流,但不能使用 HttpAsyncClient

关于java - asyc http 客户端 - Hook 来捕获响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31578000/

相关文章:

java - 来自 Apache Httpclient 的 DefaultServiceUnavailableRetryStrategy 构造函数

java - apache http 客户端 org.apache.http.NoHttpResponseException : The target server failed to respond

java - 迭代 HashMap ?

java - 在 getAudioInputStream() 期间标记/重置异常

java.lang.VerifyError : in tomcat in fedora env 错误

java - 如何在满足条件后停止值事件监听器的监听

java - 如何找到路线的所有端点(Apache Camel,Java)

Java8 Apache Http 客户端 4.5.12 - SocketException

java - Apache HttpClient 4.1 - 代理身份验证

java - 在以下使用 PoolingHttpClientConnectionManager 的 Apache HttpClient 中,如何完成资源清理?