Apache Camel HTTP component: calling services from a route
The HTTP component turns the current message into an HTTP request and the response into the next message. Headers decide more than most people expect: the method, the path, and what is sent to the server. This page explains how a request is built, then runs each important case against a local server, from error responses and timeouts to header leaks and HTTPS.
Contents
How Camel calls an HTTP service
The HTTP component, in the camel-httpto("http://host/path")platform-httpservlet
Underneath, camel-http
- Build the request URI from the endpoint URI, then let the
,CamelHttpUri andCamelHttpPath headers change it.CamelHttpQuery - Choose the method: the
option if set, else thehttpMethod header, elseCamelHttpMethod if there is a query string, elseGET if there is a body, elsePOST .GET - Copy message headers to HTTP request headers, except the ones the header filter removes, and send the body as the request entity.
- Read the response. The body becomes the new message body, the response headers become message headers, and the status code goes into
. A status outside 200 to 299 throwsCamelHttpResponseCode .HttpOperationFailedException
Steps 1 to 3 read the message headers, so a header left by an earlier step can change which URL is called and what is sent. Several sections below show this happening.
| Header or option | Effect | Default |
|---|---|---|
CamelHttpMethodhttpMethod | HTTP method | Chosen from body and query |
CamelHttpQuery | Query string, replacing the one in the URI | The URI's own |
CamelHttpPath | Path appended to the endpoint URI | None |
Content-Type | Request content type | None |
throwExceptionOnFailureokStatusCodeRange | Which status codes count as success | true200-299 |
connectTimeoutsoTimeoutresponseTimeout | Timeouts in milliseconds | 180000, 180000, none |
skipRequestHeadersheaderFilterStrategy | Which message headers become HTTP headers | All except Camel* |
followRedirects | Follow 3xx responses | false |
sslContextParameters | TLS trust and key material | The JVM defaults |
Every example is a complete program for Camel 4.23 on Java 21. Each starts a small server from the JDK's com.sun.net.httpserver
A first call: how the method is chosen
One route calls one URL four times, with different bodies and headers, to show how the producer decides the method and the query:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;
public class FirstCall {
// a stand-in for a remote service: prints what it received and answers with JSON
static HttpServer startServer() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/orders", FirstCall::handle);
server.start();
return server;
}
static void handle(HttpExchange http) throws IOException {
String body = new String(http.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
Map<String, String> headers = new TreeMap<>();
http.getRequestHeaders().forEach((name, values) -> {
if (!name.equals("Host") && !name.equals("User-agent")) {
headers.put(name, String.join(",", values));
}
});
System.out.println(" server got: " + http.getRequestMethod() + " "
+ http.getRequestURI() + (body.isEmpty() ? "" : ", body '" + body + "'"));
System.out.println(" headers : " + headers);
byte[] reply = "{\"status\":\"ok\"}".getBytes(StandardCharsets.UTF_8);
http.getResponseHeaders().add("Content-Type", "application/json");
http.sendResponseHeaders(200, reply.length);
http.getResponseBody().write(reply);
http.close();
}
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
HttpServer server = startServer();
String base = "http://localhost:" + server.getAddress().getPort();
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:orders").to(base + "/orders");
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
System.out.println("1. No body:");
Exchange reply = template.request("direct:orders", e -> e.getMessage().setBody(null));
var message = reply.getMessage();
System.out.println(" Camel got : " + message.getHeader(Exchange.HTTP_RESPONSE_CODE)
+ " " + message.getHeader(Exchange.CONTENT_TYPE) + ", body "
+ message.getBody(String.class) + " ("
+ message.getBody().getClass().getSimpleName() + ")");
System.out.println("2. A String body:");
template.requestBody("direct:orders", "2 x book");
System.out.println("3. Method, query and Content-Type from headers:");
template.requestBodyAndHeaders("direct:orders", "{\"qty\":3}", Map.of(
Exchange.HTTP_METHOD, "PUT",
Exchange.HTTP_QUERY, "id=42¬ify=true",
Exchange.CONTENT_TYPE, "application/json"));
System.out.println("4. A String body and a query, but no method header:");
template.requestBodyAndHeader("direct:orders", "2 x book",
Exchange.HTTP_QUERY, "status=open");
context.close();
server.stop(0);
}
}
1. No body:
server got: GET /orders
headers : {Accept-encoding=gzip, deflate, x-gzip, Connection=keep-alive}
Camel got : 200 application/json, body {"status":"ok"} (byte[])
2. A String body:
server got: POST /orders, body '2 x book'
headers : {Accept-encoding=gzip, deflate, x-gzip, Connection=keep-alive, Content-length=8}
3. Method, query and Content-Type from headers:
server got: PUT /orders?id=42¬ify=true, body '{"qty":3}'
headers : {Accept-encoding=gzip, deflate, x-gzip, Connection=keep-alive, Content-length=9, Content-type=application/json}
4. A String body and a query, but no method header:
server got: GET /orders?status=open
headers : {Accept-encoding=gzip, deflate, x-gzip, Connection=keep-alive}
- Call 1 had no body, so the request was a
. The reply came back withGET 200 and the server'sCamelHttpResponseCode as a header, and the body was aContent-Type that converts to abyte[] on request.String - Call 2 had a body, so the same endpoint sent a
withPOST . Nothing in the route changed: the body alone changed the method.Content-length=8 - Call 3 set the method, query and content type from headers. The server received
with a JSON content type.PUT /orders?id=42¬ify=true - Call 4 is the trap. It had a body and a query, but no method header, and the query rule comes before the body rule. The request was a
, and the bodyGET was not sent at all, with no error.2 x book
Set CamelHttpMethodhttpMethodHostUser-Agent
Message headers leak into the request
By default the producer sends every message header as an HTTP header, apart from Camel's own Camel*CamelHttpPath
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;
public class HeaderLeak {
static final Set<String> STANDARD = Set.of("Host", "User-agent", "Accept-encoding",
"Connection", "Content-length", "Content-type");
static void handle(HttpExchange http) throws IOException {
Map<String, String> custom = new TreeMap<>();
http.getRequestHeaders().forEach((name, values) -> {
if (!STANDARD.contains(name)) {
custom.put(name, String.join(",", values));
}
});
System.out.println(" server got: " + http.getRequestMethod() + " "
+ http.getRequestURI() + ", extra headers " + custom);
http.getResponseHeaders().add("X-RateLimit-Remaining", "41");
http.sendResponseHeaders(204, -1);
http.close();
}
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", HeaderLeak::handle);
server.start();
String backend = "http://localhost:" + server.getAddress().getPort() + "/audit";
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:plain").to(backend);
from("direct:cleaned")
.removeHeaders("*", "traceId")
.to(backend);
from("direct:skip").to(backend + "?skipRequestHeaders=true");
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
// headers an earlier step of the route left on the message
Map<String, Object> headers = Map.of(
"customerId", "C-1001",
"dbPassword", "s3cret",
"traceId", "t-77",
"CamelFileName", "in.csv",
Exchange.HTTP_PATH, "/api/v1/upload");
for (String route : new String[] {"plain", "cleaned", "skip"}) {
System.out.println("direct:" + route + ":");
Exchange reply = template.request("direct:" + route, e -> {
e.getMessage().setHeaders(new TreeMap<>(headers));
e.getMessage().setBody("payload");
});
System.out.println(" reply headers include X-RateLimit-Remaining="
+ reply.getMessage().getHeader("X-RateLimit-Remaining")
+ ", customerId=" + reply.getMessage().getHeader("customerId"));
}
context.close();
server.stop(0);
}
}
direct:plain:
server got: POST /audit/api/v1/upload, extra headers {Customerid=C-1001, Dbpassword=s3cret, Traceid=t-77}
reply headers include X-RateLimit-Remaining=41, customerId=C-1001
direct:cleaned:
server got: POST /audit, extra headers {Traceid=t-77}
reply headers include X-RateLimit-Remaining=41, customerId=null
direct:skip:
server got: POST /audit/api/v1/upload, extra headers {}
reply headers include X-RateLimit-Remaining=41, customerId=C-1001
sentdirect:plain ,customerId anddbPassword to the server as HTTP headers. The JDK server changes the case of header names, hencetraceId .Dbpassword was filtered out, butCamelFileName was used, so the request went toCamelHttpPath instead of/audit/api/v1/upload ./audit calleddirect:cleaned first, which removed everything exceptremoveHeaders("*", "traceId") . The request went totraceId with only that header./audit useddirect:skip , which sent no message headers at all. It did not stopskipRequestHeaders=true from changing the URL, because that header is read to build the URI, not copied.CamelHttpPath- In every case the response header
became a message header, and on the first and third routes the originalX-RateLimit-Remaining=41 header was still on the reply message.customerId
The path problem is common in routes that receive an HTTP request and pass it on to another service. Removing the CamelHttp*bridgeEndpoint=trueCamelHttpUriremoveHeaders("*")
Error responses and redirects
A status code outside the success range becomes an exception, which the route's error handler then sees. This program calls a server that answers with whatever status the path names:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.http.base.HttpOperationFailedException;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;
public class ErrorResponses {
// /status/404 answers 404, /status/302 redirects to /status/200, and so on
static void handle(HttpExchange http) throws IOException {
int code = Integer.parseInt(http.getRequestURI().getPath().substring(8));
byte[] body = ("{\"code\":" + code + "}").getBytes(StandardCharsets.UTF_8);
if (code == 302) {
http.getResponseHeaders().add("Location", "/status/200");
}
http.sendResponseHeaders(code, body.length);
http.getResponseBody().write(body);
http.close();
}
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/status/", ErrorResponses::handle);
server.start();
String base = "http://localhost:" + server.getAddress().getPort() + "/status/";
CamelContext context = new DefaultCamelContext();
context.start();
ProducerTemplate template = context.createProducerTemplate();
call(template, base + "404");
call(template, base + "500");
call(template, base + "302");
call(template, base + "302?followRedirects=true");
call(template, base + "404?throwExceptionOnFailure=false");
call(template, base + "404?okStatusCodeRange=200-299,404");
context.close();
server.stop(0);
}
static void call(ProducerTemplate template, String uri) {
System.out.println(uri.substring(uri.indexOf("/status/")) + ":");
try {
Exchange reply = template.request(uri, e -> e.getMessage().setBody(null));
if (reply.getException() != null) {
throw new CamelExecutionException("failed", reply, reply.getException());
}
System.out.println(" no exception, CamelHttpResponseCode="
+ reply.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE)
+ ", body " + reply.getMessage().getBody(String.class));
} catch (CamelExecutionException e) {
HttpOperationFailedException failure = (HttpOperationFailedException) e.getCause();
System.out.println(" " + failure.getClass().getSimpleName()
+ ": statusCode=" + failure.getStatusCode()
+ ", statusText=" + failure.getStatusText()
+ ", responseBody=" + failure.getResponseBody()
+ (failure.isRedirectError()
? ", redirect to " + failure.getRedirectLocation() : ""));
}
}
}
/status/404:
HttpOperationFailedException: statusCode=404, statusText=Not Found, responseBody={"code":404}
/status/500:
HttpOperationFailedException: statusCode=500, statusText=Internal Server Error, responseBody={"code":500}
/status/302:
HttpOperationFailedException: statusCode=302, statusText=Temporary Redirect, responseBody={"code":302}, redirect to /status/200
/status/302?followRedirects=true:
no exception, CamelHttpResponseCode=200, body {"code":200}
/status/404?throwExceptionOnFailure=false:
no exception, CamelHttpResponseCode=404, body {"code":404}
/status/404?okStatusCodeRange=200-299,404:
no exception, CamelHttpResponseCode=404, body {"code":404}
- 404 and 500 both threw
. It carries the status code, the reason phrase and the response body, so an error handler can log what the server said.HttpOperationFailedException - 302 also failed, because redirects are not followed by default and 302 is outside 200 to 299.
was true andisRedirectError() gavegetRedirectLocation() . The reason phrase/status/200 is what the JDK test server sends.Temporary Redirect - With
, the producer followed thefollowRedirects=true header and returned the 200 response.Location turned the 404 into a normal reply: no exception, the status inthrowExceptionOnFailure=false , and the error body as the message body. The route must then check the status itself, for example with aCamelHttpResponseCode .choice() treated 404 as success, which suits a lookup where "not found" is an expected answer, while 500 would still throw.okStatusCodeRange=200-299,404
HttpOperationFailedExceptionorg.apache.camel.http.basecamel-http-base
Timeouts and retries
The default timeouts are long: three minutes to connect and three minutes of silence on the socket. A slow service can hold a route thread, and a pooled connection, for that long. This program prints the defaults, calls a service that takes two seconds with a 500 ms timeout, and retries a service that fails twice with 503:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.http.HttpEndpoint;
import org.apache.camel.http.base.HttpOperationFailedException;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;
public class TimeoutsRetries {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
AtomicInteger flakyCalls = new AtomicInteger();
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/slow", http -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
http.sendResponseHeaders(204, -1);
http.close();
});
// fails with 503 twice, then succeeds
server.createContext("/flaky", http -> {
int call = flakyCalls.incrementAndGet();
System.out.println(" /flaky call " + call);
http.sendResponseHeaders(call <= 2 ? 503 : 204, -1);
http.close();
});
server.setExecutor(Executors.newCachedThreadPool());
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
onException(HttpOperationFailedException.class)
.onWhen(exceptionMessage().contains("statusCode: 503"))
.maximumRedeliveries(3)
.redeliveryDelay(100);
from("direct:slow").to(base + "/slow?responseTimeout=500");
from("direct:flaky").to(base + "/flaky");
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
HttpEndpoint defaults = context.getEndpoint(base + "/slow", HttpEndpoint.class);
System.out.println("Default timeouts: connectTimeout=" + defaults.getConnectTimeout()
+ ", soTimeout=" + defaults.getSoTimeout()
+ ", responseTimeout=" + defaults.getResponseTimeout());
System.out.println("Slow service with responseTimeout=500:");
long start = System.nanoTime();
try {
template.requestBody("direct:slow", (Object) null);
} catch (CamelExecutionException e) {
long millis = (System.nanoTime() - start) / 1000000;
System.out.println(" failed with " + e.getCause().getClass().getName());
System.out.println(" " + e.getCause().getMessage() + ", within 1 second: "
+ (millis < 1000));
}
System.out.println("Flaky service with 3 redeliveries:");
template.requestBody("direct:flaky", (Object) null);
System.out.println(" succeeded after " + flakyCalls.get() + " calls");
context.close();
server.stop(0);
}
}
Default timeouts: connectTimeout=180000, soTimeout=180000, responseTimeout=0
Slow service with responseTimeout=500:
failed with java.net.SocketTimeoutException
Read timed out, within 1 second: true
Flaky service with 3 redeliveries:
/flaky call 1
/flaky call 2
/flaky call 3
succeeded after 3 calls
andconnectTimeout are both 180000 ms, andsoTimeout is 0, meaning no separate limit.responseTimeout- With
, the call failed withresponseTimeout=500 in under a second instead of waiting two seconds.SocketTimeoutException: Read timed out - The
clause retried only failures whose message containsonException , up to three times, 100 ms apart. Calls 1 and 2 got 503 and call 3 succeeded, so the route returned normally. Other status codes, such as a 400, would fail at once, which is right: retrying a bad request cannot help.statusCode: 503
Retry only requests that are safe to repeat. A GETPOST
Sending and receiving JSON
Most HTTP services take and return JSON. With camel-jacksonmarshal().json()unmarshal().json()
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.slf4j.LoggerFactory;
public class JsonPost {
public record OrderLine(String sku, int qty) {}
public record Order(String customer, List<OrderLine> lines) {}
public record Confirmation(String orderId, String status, int items) {}
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/orders", http -> {
String json = new String(http.getRequestBody().readAllBytes(),
StandardCharsets.UTF_8);
System.out.println("server got " + http.getRequestMethod() + " with Content-Type "
+ http.getRequestHeaders().getFirst("Content-Type") + ":");
System.out.println(" " + json);
byte[] reply = "{\"orderId\":\"A-17\",\"status\":\"ACCEPTED\",\"items\":2}"
.getBytes(StandardCharsets.UTF_8);
http.getResponseHeaders().add("Content-Type", "application/json");
http.sendResponseHeaders(201, reply.length);
http.getResponseBody().write(reply);
http.close();
});
server.start();
String url = "http://localhost:" + server.getAddress().getPort() + "/orders";
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:placeOrder")
.marshal().json(JsonLibrary.Jackson)
.to(url)
.unmarshal().json(JsonLibrary.Jackson, Confirmation.class);
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
Order order = new Order("C-1001",
List.of(new OrderLine("BOOK-1", 1), new OrderLine("PEN-2", 3)));
Exchange reply = template.request("direct:placeOrder",
e -> e.getMessage().setBody(order));
Confirmation confirmation = reply.getMessage().getBody(Confirmation.class);
System.out.println("route returned " + confirmation);
System.out.println("HTTP status "
+ reply.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
context.close();
server.stop(0);
}
}
server got POST with Content-Type application/json:
{"customer":"C-1001","lines":[{"sku":"BOOK-1","qty":1},{"sku":"PEN-2","qty":3}]}
route returned Confirmation[orderId=A-17, status=ACCEPTED, items=2]
HTTP status 201
- Jackson wrote the records as
, using the record component names as JSON field names.{"customer":"C-1001","lines":[...]} - The server saw
although the route never set it: the Jackson data format sets the header when it marshals.Content-Type application/json - After marshalling, the message had a body and no method header, so the producer sent a
.POST - The reply was unmarshalled into a
record, and the 201 status was still available in the header.Confirmation
The record types are public
Dynamic URLs: to() versus toD()
A URL that contains a value from the message, such as a customer id, needs toD()to()to()toD()
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;
public class DynamicUris {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
List<String> received = new ArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", http -> {
synchronized (received) {
received.add(http.getRequestURI().toString());
}
http.sendResponseHeaders(204, -1);
http.close();
});
server.start();
String base = "http://localhost:" + server.getAddress().getPort();
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:static").to(base + "/customers/${header.id}");
from("direct:dynamic").toD(base + "/customers/${header.id}?verbose=true");
from("direct:dynamicNoOpt")
.toD().uri(base + "/customers/${header.id}?verbose=true")
.allowOptimisedComponents(false);
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
template.sendBodyAndHeader("direct:static", null, "id", 7);
System.out.println("to() with ${header.id}: server got " + received);
received.clear();
int before = context.getEndpointRegistry().size();
for (int id = 1; id <= 50; id++) {
template.sendBodyAndHeader("direct:dynamic", null, "id", id);
}
System.out.println("toD(): server got " + received.subList(0, 3) + " ... "
+ received.get(received.size() - 1));
System.out.println(" endpoints created for 50 ids: "
+ (context.getEndpointRegistry().size() - before));
before = context.getEndpointRegistry().size();
for (int id = 1; id <= 50; id++) {
template.sendBodyAndHeader("direct:dynamicNoOpt", null, "id", id);
}
System.out.println("toD() without the HTTP optimisation, endpoints created: "
+ (context.getEndpointRegistry().size() - before));
context.close();
server.stop(0);
}
}
to() with ${header.id}: server got [/customers/$%7Bheader.id%7D]
toD(): server got [/customers/1?verbose=true, /customers/2?verbose=true, /customers/3?verbose=true] ... /customers/50?verbose=true
endpoints created for 50 ids: 1
toD() without the HTTP optimisation, endpoints created: 50
withto() sent the expression literally: the server received${header.id} . Camel did not treat it as an error./customers/$%7Bheader.id%7D evaluated the expression for each message, so the server receivedtoD() to/customers/1 ./customers/50- Those 50 URLs created only one endpoint. The HTTP component is
: forSendDynamicAware it keeps one endpoint for the host and moves the path and query into thetoD() andCamelHttpPath headers.CamelHttpQuery - With that optimisation turned off, through
, each id created its own endpoint: 50 for 50 ids. Each endpoint holds a producer, and with ids from real traffic the count keeps growing until the cache limit.allowOptimisedComponents(false)
The optimisation is on by default, so toD()
HTTPS with your own trust store
HTTPS works with the same component: use an https://keytool
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpsServer;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.jsse.KeyStoreParameters;
import org.apache.camel.support.jsse.SSLContextParameters;
import org.apache.camel.support.jsse.TrustManagersParameters;
import org.slf4j.LoggerFactory;
public class HttpsCall {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
Path keystore = Files.createTempDirectory("tls").resolve("server.p12");
// a self-signed certificate for localhost, made with the JDK's keytool
Process keytool = new ProcessBuilder(
Path.of(System.getProperty("java.home"), "bin", "keytool").toString(),
"-genkeypair", "-alias", "server", "-keyalg", "RSA", "-keysize", "2048",
"-dname", "CN=localhost", "-ext", "SAN=dns:localhost", "-validity", "2",
"-storetype", "PKCS12", "-keystore", keystore.toString(),
"-storepass", "changeit").redirectErrorStream(true).start();
keytool.getInputStream().transferTo(OutputStream.nullOutputStream());
System.out.println("keytool exit code: " + keytool.waitFor());
HttpsServer server = startServer(keystore);
String url = "https://localhost:" + server.getAddress().getPort() + "/secure";
CamelContext context = new DefaultCamelContext();
KeyStoreParameters trustStore = new KeyStoreParameters();
trustStore.setResource("file:" + keystore);
trustStore.setPassword("changeit");
trustStore.setType("PKCS12");
TrustManagersParameters trustManagers = new TrustManagersParameters();
trustManagers.setKeyStore(trustStore);
SSLContextParameters tls = new SSLContextParameters();
tls.setTrustManagers(trustManagers);
context.getRegistry().bind("serverTrust", tls);
context.start();
ProducerTemplate template = context.createProducerTemplate();
System.out.println("Without a trust store:");
try {
template.requestBody(url, (Object) null, String.class);
} catch (CamelExecutionException e) {
Throwable cause = e.getCause();
System.out.println(" " + cause.getClass().getSimpleName() + ": "
+ cause.getMessage().substring(0, cause.getMessage().indexOf(':')));
}
System.out.println("With sslContextParameters=#serverTrust:");
System.out.println(" " + template.requestBody(url + "?sslContextParameters=#serverTrust",
(Object) null, String.class));
context.close();
server.stop(0);
}
static HttpsServer startServer(Path keystore) throws Exception {
KeyStore keys = KeyStore.getInstance("PKCS12");
try (InputStream in = Files.newInputStream(keystore)) {
keys.load(in, "changeit".toCharArray());
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
kmf.init(keys, "changeit".toCharArray());
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(kmf.getKeyManagers(), null, null);
HttpsServer server = HttpsServer.create(new InetSocketAddress("localhost", 0), 0);
server.setHttpsConfigurator(new HttpsConfigurator(ssl));
server.createContext("/secure", http -> {
byte[] reply = ("hello over "
+ ((HttpsExchange) http).getSSLSession().getProtocol())
.getBytes(StandardCharsets.UTF_8);
http.sendResponseHeaders(200, reply.length);
http.getResponseBody().write(reply);
http.close();
});
server.start();
return server;
}
}
keytool exit code: 0
Without a trust store:
SSLHandshakeException: (certificate_unknown) PKIX path building failed
With sslContextParameters=#serverTrust:
hello over TLSv1.3
- Without a trust store, the TLS handshake failed with
andSSLHandshakeException : no certificate in the JVM's default trust store signed the server's certificate.PKIX path building failed - With
, Camel built ansslContextParameters=#serverTrust that trusts the certificate from the keystore, and the call succeeded over TLS 1.3.SSLContext - The certificate's subject alternative name,
, matches the host name in the URL, so host name verification passed.dns:localhost
SSLContextParametersx509HostnameVerifier=#noopNoopHostnameVerifier
Choosing how to call HTTP services
| Situation | What to use |
|---|---|
| Any call whose method matters | CamelHttpMethodhttpMethod |
| Calling an outside service from a route that has other headers | removeHeaders("*") |
| Proxying an incoming HTTP request to a backend | bridgeEndpoint=true |
| 404 is a normal answer | okStatusCodeRange=200-299,404 |
| The route inspects every status itself | throwExceptionOnFailure=falsechoice()CamelHttpResponseCode |
| Services that are sometimes slow | Explicit connectTimeoutresponseTimeout |
| Temporary failures such as 503 | onException |
| A URL that contains message values | toD() |
| JSON APIs | marshal().json()unmarshal().json(Type.class)camel-jackson |
| Private CA or mutual TLS | sslContextParameters |
The traps to remember are the method rule, where a query string turns a POSTGET