We use Apache Camel to glue services together. Camel Restlet can help you to translate a bean call into a REST call and vice versa. As we started using it we came to a need to add custom headers to a REST call. We thought it must be an easy job but it ended up digging deep into the Restlet source code to find a solution.
But first: Thanks to Lukas Eberli for his digging. He finally found the solution!
To be honest we didn’t read the documentation first. We just had a look at the API. I’m sure you work the same way. But what you get if you inspect the Camel interface
ProducerTemplate is a massive amount of methods (more than 80!). OK, let’s just concentrate on the 10 (!) overloads of
sendBodyAndHeaders – or should I use
requestBodyAndHeaders? This two have both a parameter
headers of the type
Map. But don’t think you could just put your own headers into this map. That won’t work. Your headers will just disappear somewhere deep in Restlets code. The only possibility to put your own headers into the http request is this:
// some needed imports import org.restlet.util.Series; import org.restlet.data.Header; import org.restlet.engine.http.header.HeaderConstants; ... // create the header map as an argument for // the producer template: Map<String, Object> headers = new HashMap<>(); // create the header series where you put your // custom headers Series <header>userDefinedHeaders = new Series <header>(Header.class); userDefinedHeaders.add(new Header("x-my-header", myHeaderValue));</header></header>// tell Restlet to add custom headers by using the // ATTRIBUTE_HEADERS constant. headers.put(HeaderConstants.ATTRIBUTE_HEADERS, userDefinedHeaders); // finally call the send method producerTemplate.sendBodyAndHeaders(endpoint, body, headers);
Unfortunately we could not find any documentation pointing to this. Only digging into the code of Restlet reveals this features. I am also disappointed of the giant interface ProducerTemplate. The lack of types puts you into type casting everything. I thought apache guys would do better than this. There is obviously a lot to improve…