Apache Camel Rest DSL参数传递问题:Weather API获取城市天气失败
解决Apache Camel Weather API传递Header参数的问题
首先先确认Header参数是否真的传递到了direct:weather路由中,建议先添加日志输出所有Header,排查参数是否存在:
from("direct:weather") .log("Received headers: ${headers}") // 打印所有Header,确认city和country是否存在 .log("Get weather by city") .to("weather:foo?location=${header.city},${header.country}&appid=8bb3bc2e4efb92992ed3e7190&units=metric") .log("Weather: ${body}");
如果日志中能看到city和country的Header,但Weather API调用仍报错,大概率是参数拼接或组件表达式解析的问题,可以尝试以下修正方案:
方案1:提前组装完整的location参数
通过setHeader将city和country拼接成合法的location字符串,再传递给Weather组件,这种方式更直观且便于调试,同时能处理country为空的情况:
from("direct:weather") .log("Get weather by city") // 组装location,避免country为空时出现多余逗号 .setHeader("weatherLocation", simple("${header.city}${header.country != null ? ',' + header.country : ''}")) .to("weather:foo?location=${header.weatherLocation}&appid=8bb3bc2e4efb92992ed3e7190&units=metric") .log("Weather: ${body}");
方案2:使用完整的Exchange Header表达式
部分Camel版本对${header.xxx}简写的支持可能存在兼容问题,换成完整的${exchange.header.xxx}表达式尝试:
from("direct:weather") .log("Get weather by city") .to("weather:foo?location=${exchange.header.city},${exchange.header.country}&appid=8bb3bc2e4efb92992ed3e7190&units=metric") .log("Weather: ${body}");
方案3:明确Rest路由的Header参数规则
在Rest定义中显式标记参数是否必填,同时确保客户端请求确实携带了对应Header:
.get("/weather").description("Get weather by city") .param().name("city").type(RestParamType.header).description("The city name").dataType("string").required(true).endParam() .param().name("country").type(RestParamType.header).description("The country name").dataType("string").required(false).endParam() .to("direct:weather");
内容的提问来源于stack exchange,提问作者cihad
相关产品推荐
相关产品推荐

