You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vert.x反向代理中捕获HTTP响应为明文

解决Vert.x反向代理捕获响应明文的问题

要捕获响应明文,你需要在handleProxyResponse方法中通过ProxyResponse的body()方法获取响应体的Future<Buffer>,处理完成后再将响应发送出去。以下是修改后的完整代码:

public Future start(Vertx vertx) {
    HttpClient proxyClient = vertx.createHttpClient();

    HttpProxy proxy = HttpProxy.reverseProxy(proxyClient);
    proxy.origin(targetPort, targetHost);
    
    // 拦截请求并记录请求体
    proxy.addInterceptor(new ProxyInterceptor() {
        @Override
        public Future<ProxyResponse> handleProxyRequest(ProxyContext context) {
            ProxyRequest proxyRequest = context.request();
            HttpServerRequest originalRequest = proxyRequest.proxiedRequest();
            
            originalRequest.bodyHandler(requestBody -> {
                LOG.info("Request Body: {}", requestBody.toString("UTF-8"));
            });
            
            return context.sendRequest();
        }
    });

    // 拦截响应并记录响应体
    proxy.addInterceptor(new ProxyInterceptor() {
        @Override
        public Future<Void> handleProxyResponse(ProxyContext context) {
            ProxyResponse proxyResponse = context.response();
            
            // 获取响应体的Future,处理完成后记录并发送响应
            return proxyResponse.body()
                .onSuccess(responseBody -> {
                    // 记录响应明文
                    LOG.info("Response Body: {}", responseBody.toString("UTF-8"));
                })
                // 处理完成后继续发送响应到客户端
                .compose(v -> proxyResponse.send());
        }
    });

    HttpServer proxyServer = vertx.createHttpServer();
    return proxyServer.requestHandler(proxy).listen(listeningPort).mapEmpty();
}

关键说明:

  • ProxyResponse.body()方法会返回一个Future<Buffer>,当响应体完全接收后触发成功回调,此时可将Buffer转为字符串记录明文。
  • 处理完响应体后必须调用proxyResponse.send(),确保响应能正常转发给客户端,维持代理流程的完整性。
  • 将listen的结果通过mapEmpty()转为Future<Void>,保证方法返回的Future能正确反映代理服务的启动状态。

内容的提问来源于stack exchange,提问作者siva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:58:27