Send POST Request using Apache Camel

user6641655 picture user6641655 · Mar 2, 2017 · Viewed 21.2k times · Source

I was able to send a GET request using Apache Camel to a REST service and now I'm trying to send a POST request with a JSON body using Apache Camel. I wasn't able to figure out how to add the JSON body and send the request. How can I add a JSON body, send the request and get the response code?

Answer

kris_k picture kris_k · Mar 7, 2017

Below you can find a sample Route which sends (every 2 seconds) the json, using POST method to the server, in the example it is localhost:8080/greeting. There is also a way to get the response presented:

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

Usually it is not a good idea to prepare json manually. You can use e.g.

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-gson</artifactId>
</dependency>

to perform marshalling for you. Assuming you have a Greeting class defined you can modify the Route by removing the first processor and using the following code instead:

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

Further reading: http://camel.apache.org/http.html It is worth noting that there is also http4 component (they use different version of Apache HttpClient under the hood).