下面是一个使用Apache Camel进行REST调用外部服务的代码示例:
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class RestCallExample {
public static void main(String[] args) throws Exception {
// 创建Camel上下文
CamelContext camelContext = new DefaultCamelContext();
// 添加路由
camelContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
// 定义REST调用的路由
rest("/api")
.get("/hello") // GET请求
.to("http://api.example.com/hello"); // 调用外部服务
// 处理外部服务的响应
from("http://api.example.com/hello")
.log("Response: ${body}");
}
});
// 启动Camel上下文
camelContext.start();
// 保持Camel上下文运行
Thread.sleep(5000);
// 停止Camel上下文
camelContext.stop();
}
}
上述代码示例创建了一个Apache Camel上下文,并在其中定义了一个REST调用的路由。该路由监听/api/hello
的GET请求,并将请求转发到http://api.example.com/hello
外部服务。然后,从外部服务获取响应,并将响应日志输出。
你可以根据需要修改路由的定义,并在from
方法的参数中替换为你想要调用的外部服务的URL。