Always Thinking
Always Thinking

Reputation: 65

How to call REST with POST in Apache camel?

I want to call a REST API with Apache Camel.

When I do it from Postman I use the following:

Method: Post
Headers: 
Content-Type: application/x-www-form-urlencoded

Body
Check x-www-form-urlencoded option

3 Key value parameters added
Username: ABC
Password: ABC
Country: UK

After setting up this configuration I am able to consume my REST API and it responds with an XML.

But I really don't know how to write this on Camel.

Upvotes: 2

Views: 9947

Answers (2)

Ricardo Zanini
Ricardo Zanini

Reputation: 1151

Just to add to the @marcin-pietraszek precise answer and based on your last comment:

how can I add Body (Username: ABC, Password: ABC, Country: UK) parameters inside your code have shared

Depends on the services' interface. If it's query parameters, you could use:

from("direct:start").
    setHeader(Exchange.HTTP_METHOD, constant("POST")).
    setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded")).
    setHeader(Exchange.HTTP_QUERY, constant("Username=ABC&Password=ABC&Country=UK"))
    to("http://www.google.com");

If it's directly in the body you could use:

from("direct:start").
    setHeader(Exchange.HTTP_METHOD, constant("POST")).
    setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded")).
    setBody(constant("Username: ABC, Password: ABC, Country: UK"))
    to("http://www.google.com");

Remind that you should look into the service you are posting how it expect to receive the body (JSON, XML, CSV, etc.).

Upvotes: 5

Marcin Pietraszek
Marcin Pietraszek

Reputation: 3214

Documentation provides an example:

from("direct:start").
    setHeader(Exchange.HTTP_METHOD, constant("POST")).
    setHeader(Exchange.CONTENT_TYPE, constant("application/x-www-form-urlencoded")).
    to("http://www.google.com");

I assume that you could also use setBody method there ;).

Upvotes: 3

Related Questions