发送骆驼 HTTP 帖子自定义正文



我是Apache骆驼的新手。我正在尝试创建路由来调用多个 rest API 并将响应聚合为一个。但由于某种原因,我正在创建的 JSON 请求没有到达其余端点。在调试期间,我看到 Exchange 对象确实具有我设置的值并转换为字节数组,另一方面,rest API 接收空对象。

我正在开发一个 Spring 引导项目,我已经尝试了不同的方法来将请求编组到 JSON,包括 Gson 和 Jackson。这些似乎都不起作用。

请协助。

from("direct:oneResponse")
        .multicast(new MyAggregationStrategy()).parallelProcessing()
        .to("direct:rest1call", "direct:rest2call")
        .end();

from("direct:rest1call")
        .routeId("rest1call")
        .setHeader(Exchange.HTTP_METHOD, constant("POST"))
        .setHeader("Content-Type", constant("application/json"))
        .setHeader("Accept", constant("application/json"))
        .process(new Processor() {              
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody(<<valid json>>); //json values as required for the rest call.
            }
        })
        .to("http4://localhost:5555/mock/rest1call")
        .setProperty("route", simple("routeId"))
        .unmarshal(new JacksonDataFormat(Rest1Response.class));
from("direct:rest2call")
        .routeId("rest2call")
        .setHeader(Exchange.HTTP_METHOD, constant("POST"))
        .setHeader("Content-Type", constant("application/json"))
        .setHeader("Accept", constant("application/json"))
        .process(new Processor() {              
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setBody(<<valid json>>); //json values as required for the rest call.
            }
        })
        .to("http4://localhost:5555/mock/rest2call")
        .setProperty("route", simple("routeId"))
        .unmarshal(new JacksonDataFormat(Rest2Response.class));

您可以尝试创建一个处理器并指定其中的所有标头和正文吗?

.process(new Processor() {              
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getOut().setHeader(Exchange.HTTP_METHOD, HttpMethod.POST);
                exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
                exchange.getOut().setHeader("Accept", "application/json");
                /* this is one way, string representation of json, but maybe you can try to build Model and fill that model with data */
                exchange.getIn().setBody(<<valid json>>); //json values as required for the rest call.
            }
        })

如果您决定使用模型,请在处理器后使用封送处理,以确保您的数据已转换为 JSON。

.marshal(yourDataFormat)

试试GsonDataFormat,它对我来说效果很好。

最新更新