8
votes

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?

4

4 Answers

9
votes

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

2
votes

This is how you can do it:

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

Current Camel Exchange's body will get POSTED to the URL end point.

2
votes
//This code is for sending post request and getting response
public static void main(String[] args) throws Exception {
    CamelContext c=new DefaultCamelContext();       
    c.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {          
            from("direct:start")
            .process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                System.out.println("i am worlds fastest flagship processor ");
                exchange.getIn().setHeader("CamelHttpMethod", "POST");
                exchange.getIn().setHeader("Content-Type", "application/json");
                exchange.getIn().setHeader("accept", "application/json");
                }
                })
              // to the http uri
                .to("https://www.google.com")
       // to the consumer
                .to("seda:end");
        }
    });



    c.start();
    ProducerTemplate pt = c.createProducerTemplate();
      // for sending request 
    pt.sendBody("direct:start","{\"userID\": \"678\",\"password\": \"password\", 
  \"ID\": \"123\"  }");
    ConsumerTemplate ct = c.createConsumerTemplate();
    String m = ct.receiveBody("seda:end",String.class);
    System.out.println(m);
}
1
votes

Note that while you may prefer to explicitly set the HTTP method, you don't have to. The following is from Camel's http component documentation:

WHICH HTTP METHOD WILL BE USED

The following algorithm is used to determine what HTTP method should be used:

  1. Use method provided as endpoint configuration (httpMethod).
  2. Use method provided in header (Exchange.HTTP_METHOD).
  3. GET if query string is provided in header.
  4. GET if endpoint is configured with a query string.
  5. POST if there is data to send (body is not null).
  6. GET otherwise.

In other words, if you have a body/data and conditions 1-4 don't apply, it will POST by default. This is working on routes I've implemented.