gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:17:54 25 4
gpt4 key购买 nike

我们的应用程序对 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com