首页 > 解决方案 > Camel Routes - 如何将正文响应返回为 xml

问题描述

首先,我是 Spring Boot 的新手。我不确定是否可能,但我想从外部 url 返回 xml 响应。

我有这个代码:

@GetMapping("/myPage")
public void myPage() {
    restConfiguration().host("localhost").port(8080);
    from("timer://runOnce?repeatCount=1&delay=0")
            .to("rest:get:/external-page")
            .to("stream:out");
}

myPage() 正在返回一个 XML(没关系)。因此,现在我想在执行此操作时返回相同的 XML:

curl http://localhost/myPage

我不确定是否必须使用.to("stream:out"),但 curl 返回一个空结果。

有人能帮我吗?提前致谢。

标签: spring-bootapache-camelspring-camel

解决方案


我找到了解决方案,这就是如何获得响应。

CamelContext context = new DefaultCamelContext();
    context.addRoutes(new RouteBuilder() {
        public void configure() {
            restConfiguration().host(sHost).port(iPort);
            from("direct:start")
                    .setHeader(Exchange.HTTP_METHOD,simple("GET"))
                    .to("rest:get:/external-page");
        }
    });

    context.start();

    ProducerTemplate template = context.createProducerTemplate();
    String headerValue = "application/xml";

    Map<String, Object> headers = new HashMap<String,Object>();
    headers.put("Content-Type", headerValue);

    Object result = template.requestBodyAndHeaders("direct:start", null, headers, String.class);
    Exchange exchange = new DefaultExchange(context);
    String response = ExchangeHelper.convertToType(exchange, String.class, result);
    context.stop();

    return response;

推荐阅读