使用Apache Camel发送POST请求

use*_*655 6 java rest post apache-camel camel-http

我能够使用Apache Camel将GET请求发送到REST服务,现在我正尝试使用Apache Camel发送具有JSON正文的POST请求。我无法弄清楚如何添加JSON正文和发送请求。如何添加JSON正文,发送请求并获取响应代码?

kri*_*s_k 6

在下面,您可以找到一个示例路由,该示例路由使用POST方法(每2秒发送一次)将json发送到服务器,在示例中为localhost:8080 / greeting。还有一种获取响应的方法:

from("timer://test?period=2000")
    .process(exchange -> exchange.getIn().setBody("{\"title\": \"The title\", \"content\": \"The content\"}"))
    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .to("http://localhost:8080/greeting")
    .process(exchange -> log.info("The response code is: {}", exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE)));
Run Code Online (Sandbox Code Playgroud)

通常,手动准备json不是一个好主意。您可以使用例如

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-gson</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

进行编组为您服务。假设你有一个问候类中定义的,可以通过删除所述第一处理器和使用下面的代码,而不是修改路线:

.process(exchange -> exchange.getIn().setBody(new Greeting("The title2", "The content2")))
.marshal().json(JsonLibrary.Gson)
Run Code Online (Sandbox Code Playgroud)

进一步阅读:http : //camel.apache.org/http.html值得注意的是,还有http4组件(它们在后台使用了不同版本的Apache HttpClient)。


小智 4

您可以这样做:

from("direct:start")
 .setHeader(Exchange.HTTP_METHOD, constant("POST"))
 .to("http://www.google.com");
Run Code Online (Sandbox Code Playgroud)

当前 Camel Exchange 的正文将被 POSTED 到 URL 端点。