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

为何开启流缓存后Camel HTTP请求返回的响应体仍为空?

Camel HTTPS组件调用后响应流有数据但无法直接转换为DTO问题解决方案

根因说明

Apache Camel的HTTPS组件默认会将接口返回的响应包装为CachedOutputStream缓存流以支持重复读取,但类型转换器不会自动触发底层字节流的反序列化动作,因此直接调用getMessage(DocumentResponseDto.class)会返回空值,与你直接用RestTemplate调用时RestTemplate自动完成流读取、反序列化的逻辑不同。

可行解决方案

方案1:聚合策略内显式读取流并反序列化

直接在AggregationStrategy开头先读取响应流为字符串,再手动反序列化为目标DTO即可:

private static final AggregationStrategy finalizeImageProcess = (request, response) -> {
    // 触发缓存流读取,获取原始响应JSON字符串
    String responseJson = response.getIn().getBody(String.class);
    // 手动反序列化,若项目已经注册了全局ObjectMapper可以直接注入复用
    DocumentResponseDto responseDto = new ObjectMapper().readValue(responseJson, DocumentResponseDto.class);
    var documentId = responseDto.getIntId();
    // 原有业务逻辑保持不变
    var imageProcess = request.getIn().getHeader("image-process",ImageProcess.class);
    imageProcess.setDocumentId(documentId);
    imageProcess.setDocumentIdReceivedTime(LocalDateTime.now(ZoneId.of("America/New_York")));

    imageProcess.setImageStatus("complete");
    imageProcess.setStepNote(null);
    var step = Optional.ofNullable(request.getIn().getHeader(STEP)).map(String::valueOf).orElse(null);
    imageProcess.setStep(step);

    return request;
};

方案2:HTTPS端点指定响应 payload 类型,自动完成反序列化

在调用enrich的HTTPS请求地址后追加responsePayloadType参数,指定返回值的目标类型,Camel会自动完成流读取和反序列化动作:

// 拼接响应类型参数
String requestEndpoint = auditorProps.getBaseUrl() + auditorProps.getPath() 
        + "?responsePayloadType=" + DocumentResponseDto.class.getName();
.enrich(requestEndpoint, finalizeImageProcess);

配置完成后,AggregationStrategy内直接调用response.getMessage(DocumentResponseDto.class)即可拿到正确的DTO对象。

方案3:新增unmarshal步骤处理响应

如果不想修改聚合策略和请求地址,也可以将enrich拆分为to调用+unmarshal步骤:

.to(auditorProps.getBaseUrl() + auditorProps.getPath())
.unmarshal().json(DocumentResponseDto.class)
// 后续处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:36:04