发送骆驼HTTP Post自定义正文

时间:2019-01-02 12:01:15

标签: java http spring-boot apache-camel

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

我正在研究Spring引导项目,并且尝试了包括Gson和Jackson在内的不同方式将请求封送给JSON。似乎都不起作用。

请协助。

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));

1 个答案:

答案 0 :(得分:0)

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

.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对我来说很好。