Camel执行HTTP/HTTPS4调用后如何获取响应状态码?
获取Camel HTTP/HTTPS4调用的响应状态码
嘿,作为Camel新手,这问题真的很典型!不管是用http还是https4组件(毕竟https4就是带SSL支持的HTTP组件,用法基本一致),获取响应状态码的核心逻辑都是一样的——Camel会自动把状态码存入Exchange的消息头中,咱们直接读取就行。
核心原理
Camel在完成HTTP/HTTPS调用后,会将响应状态码存储在消息头Exchange.HTTP_RESPONSE_CODE(对应的字符串键是"CamelHttpResponseCode")里。这个值是Integer类型,覆盖了所有合法的HTTP状态码(2xx、3xx、4xx、5xx)。
Java DSL 示例
下面是一个用https4组件调用并获取状态码的完整例子:
import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; public class HttpStatusRoute extends RouteBuilder { @Override public void configure() throws Exception { from("direct:invokeHttpsEndpoint") // 调用HTTPS接口 .to("https4://your-target-api.com/resource") // 处理响应,读取状态码 .process(exchange -> { Integer statusCode = exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class); // 根据状态码分支处理 if (statusCode != null) { System.out.println("Received HTTP status code: " + statusCode); if (statusCode >= 200 && statusCode < 300) { // 处理成功响应,比如解析响应体 String responseBody = exchange.getIn().getBody(String.class); System.out.println("Success response body: " + responseBody); } else { // 处理错误状态,比如404、500 System.out.println("Error occurred with status code: " + statusCode); } } else { // 状态码为空,说明调用过程中发生了连接异常(比如DNS失败、超时) System.out.println("Failed to connect to the endpoint, no status code returned"); } }); } }
XML DSL 示例
如果是用Spring XML配置路由,同样可以直接通过消息头获取:
<routes xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="direct:invokeHttpsEndpoint"/> <to uri="https4://your-target-api.com/resource"/> <!-- 直接打印状态码 --> <log message="HTTP Response Code: ${header.CamelHttpResponseCode}"/> <!-- 根据状态码做分支处理 --> <choice> <when> <simple>${header.CamelHttpResponseCode} between 200 and 299</simple> <to uri="direct:handleSuccess"/> </when> <when> <simple>${header.CamelHttpResponseCode} between 400 and 499</simple> <to uri="direct:handleClientError"/> </when> <when> <simple>${header.CamelHttpResponseCode} between 500 and 599</simple> <to uri="direct:handleServerError"/> </when> <otherwise> <to uri="direct:handleUnexpectedStatus"/> </otherwise> </choice> </route> </routes>
注意事项
- 异常场景处理:如果调用过程中发生了无法连接、超时等异常,Camel不会设置
CamelHttpResponseCode头,而是会抛出HttpOperationFailedException(针对HTTP组件)。你可以通过onException来捕获这类异常:onException(HttpOperationFailedException.class) .log("HTTP call failed: ${exception.message}") .handled(true) .to("direct:handleConnectionError"); - 版本兼容性:
Exchange.HTTP_RESPONSE_CODE常量在Camel 2.x和3.x/4.x中都存在,直接引用即可;如果不想引入类,用字符串"CamelHttpResponseCode"也完全没问题。
内容的提问来源于stack exchange,提问作者Susanna Michael
相关产品推荐
相关产品推荐

