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-http artifact, lets a route call an HTTP or HTTPS server. It is a producer only: to("http://host/path") sends the current message as a request and replaces the message with the response. Routes that receive HTTP requests use a consumer component instead, such as platform-http or servlet, usually through the REST DSL.

Underneath, camel-http uses Apache HttpClient 5 (version 5.6 with Camel 4.23), with a pooled connection manager shared by the component. For each exchange, the producer works in four steps:

  1. Build the request URI from the endpoint URI, then let the CamelHttpUri, CamelHttpPath and CamelHttpQuery headers change it.
  2. Choose the method: the httpMethod option if set, else the CamelHttpMethod header, else GET if there is a query string, else POST if there is a body, else GET.
  3. Copy message headers to HTTP request headers, except the ones the header filter removes, and send the body as the request entity.
  4. Read the response. The body becomes the new message body, the response headers become message headers, and the status code goes into CamelHttpResponseCode. A status outside 200 to 299 throws 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.

Headers and options that control a call
Header or optionEffectDefault
CamelHttpMethod header, httpMethod optionHTTP methodChosen from body and query
CamelHttpQuery headerQuery string, replacing the one in the URIThe URI's own
CamelHttpPath headerPath appended to the endpoint URINone
Content-Type headerRequest content typeNone
throwExceptionOnFailure, okStatusCodeRangeWhich status codes count as successtrue, 200-299
connectTimeout, soTimeout, responseTimeoutTimeouts in milliseconds180000, 180000, none
skipRequestHeaders, headerFilterStrategyWhich message headers become HTTP headersAll except Camel* and a few others
followRedirectsFollow 3xx responsesfalse
sslContextParametersTLS trust and key materialThe 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 package on a free port, as a stand-in for a remote service, and turns Camel's logging off. The server prints what it received, so the output shows the real request on the wire.

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:

Java
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&notify=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);
    }
}
Output
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&notify=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 GET. The reply came back with CamelHttpResponseCode 200 and the server's Content-Type as a header, and the body was a byte[] that converts to a String on request.
  • Call 2 had a body, so the same endpoint sent a POST with Content-length=8. Nothing in the route changed: the body alone changed the method.
  • Call 3 set the method, query and content type from headers. The server received PUT /orders?id=42&notify=true with a JSON content type.
  • 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 GET, and the body 2 x book was not sent at all, with no error.

Set CamelHttpMethod, or httpMethod on the endpoint, whenever a call should not depend on what happens to be in the body. The program hides the Host header, which contains the port, and User-Agent, which contains the Java version.

Message headers leak into the request

By default the producer sends every message header as an HTTP header, apart from Camel's own Camel* headers. In a real route, headers come from many places: a file consumer, a JMS message, a previous HTTP call, or values the route stored itself. This program puts five such headers on a message, including a database password and a CamelHttpPath header that an HTTP consumer earlier in the route would have set, and sends it through three routes:

Java
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);
    }
}
Output
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
  • direct:plain sent customerId, dbPassword and traceId to the server as HTTP headers. The JDK server changes the case of header names, hence Dbpassword. CamelFileName was filtered out, but CamelHttpPath was used, so the request went to /audit/api/v1/upload instead of /audit.
  • direct:cleaned called removeHeaders("*", "traceId") first, which removed everything except traceId. The request went to /audit with only that header.
  • direct:skip used skipRequestHeaders=true, which sent no message headers at all. It did not stop CamelHttpPath from changing the URL, because that header is read to build the URI, not copied.
  • In every case the response header X-RateLimit-Remaining=41 became a message header, and on the first and third routes the original customerId header was still on the reply message.

The path problem is common in routes that receive an HTTP request and pass it on to another service. Removing the CamelHttp* headers before the call fixes it; bridgeEndpoint=true also makes the producer ignore CamelHttpUri, and is meant for proxy routes that should forward the incoming path. A safe default for calls to outside services is removeHeaders("*"), followed by setting only the headers the service needs.

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:

Java
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() : ""));
        }
    }
}
Output
/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 HttpOperationFailedException. It carries the status code, the reason phrase and the response body, so an error handler can log what the server said.
  • 302 also failed, because redirects are not followed by default and 302 is outside 200 to 299. isRedirectError() was true and getRedirectLocation() gave /status/200. The reason phrase Temporary Redirect is what the JDK test server sends.
  • With followRedirects=true, the producer followed the Location header and returned the 200 response.
  • throwExceptionOnFailure=false turned the 404 into a normal reply: no exception, the status in CamelHttpResponseCode, and the error body as the message body. The route must then check the status itself, for example with a choice().
  • okStatusCodeRange=200-299,404 treated 404 as success, which suits a lookup where "not found" is an expected answer, while 500 would still throw.

HttpOperationFailedException is in the org.apache.camel.http.base package, from camel-http-base, which other HTTP components share.

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:

Java
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);
    }
}
Output
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
  • connectTimeout and soTimeout are both 180000 ms, and responseTimeout is 0, meaning no separate limit.
  • With responseTimeout=500, the call failed with SocketTimeoutException: Read timed out in under a second instead of waiting two seconds.
  • The onException clause retried only failures whose message contains statusCode: 503, 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.

Retry only requests that are safe to repeat. A GET is, but a POST that timed out may have been processed by the server, and sending it again can create a duplicate order. Use an idempotency key in a header, if the service supports one, before retrying writes. The redelivery options are covered in Camel error handling, and a circuit breaker for services that stay down is on the Camel throttler page.

Sending and receiving JSON

Most HTTP services take and return JSON. With camel-jackson on the classpath, marshal().json() turns a Java object into JSON before the call and unmarshal().json() turns the reply back into an object. An order with two lines is enough to see the nested structure:

Java
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);
    }
}
Output
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 {"customer":"C-1001","lines":[...]}, using the record component names as JSON field names.
  • The server saw Content-Type application/json although the route never set it: the Jackson data format sets the header when it marshals.
  • After marshalling, the message had a body and no method header, so the producer sent a POST.
  • The reply was unmarshalled into a Confirmation record, and the 201 status was still available in the header.

The record types are public because Jackson creates them by reflection. More formats, including XML and CSV, are on the Camel data formats page.

Dynamic URLs: to() versus toD()

A URL that contains a value from the message, such as a customer id, needs toD(). A plain to() resolves its URI once, when the route starts. This program calls one URL with to() and fifty with toD(), and counts the endpoints Camel creates:

Java
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);
    }
}
Output
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
  • to() with ${header.id} sent the expression literally: the server received /customers/$%7Bheader.id%7D. Camel did not treat it as an error.
  • toD() evaluated the expression for each message, so the server received /customers/1 to /customers/50.
  • Those 50 URLs created only one endpoint. The HTTP component is SendDynamicAware: for toD() it keeps one endpoint for the host and moves the path and query into the CamelHttpPath and CamelHttpQuery headers.
  • With that optimisation turned off, through allowOptimisedComponents(false), 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.

The optimisation is on by default, so toD() with HTTP URLs is safe. With components that do not have it, keep the dynamic part out of the URI: send to one fixed endpoint and pass the varying value in a header that the component reads.

HTTPS with your own trust store

HTTPS works with the same component: use an https:// URI. The JVM's default trust store decides which servers are trusted, so a service with a certificate from a private CA fails until you supply a trust store. This program makes a self-signed certificate with the JDK's keytool, serves HTTPS with it, and calls the server twice:

Java
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;
    }
}
Output
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 SSLHandshakeException and PKIX path building failed: no certificate in the JVM's default trust store signed the server's certificate.
  • With sslContextParameters=#serverTrust, Camel built an SSLContext that trusts the certificate from the keystore, and the call succeeded over TLS 1.3.
  • The certificate's subject alternative name, dns:localhost, matches the host name in the URL, so host name verification passed.

SSLContextParameters also takes key managers, for services that require a client certificate (mutual TLS). It can be set on the component, which then applies to all its endpoints, or per endpoint as here. Turning off the checks, with x509HostnameVerifier=#noop bound to a NoopHostnameVerifier or with a trust manager that accepts everything, is sometimes suggested for testing. It also accepts an attacker's certificate, so never ship it. For HTTP calls without Camel, see the Java HttpClient page.

Choosing how to call HTTP services

Common situations and what fits them
SituationWhat to use
Any call whose method mattersCamelHttpMethod header or httpMethod option, never the body rule
Calling an outside service from a route that has other headersremoveHeaders("*"), then set only the headers needed
Proxying an incoming HTTP request to a backendbridgeEndpoint=true, aware that the incoming path is forwarded
404 is a normal answerokStatusCodeRange=200-299,404
The route inspects every status itselfthrowExceptionOnFailure=false and a choice() on CamelHttpResponseCode
Services that are sometimes slowExplicit connectTimeout and responseTimeout
Temporary failures such as 503onException with redelivery, for safe requests only
A URL that contains message valuestoD()
JSON APIsmarshal().json() and unmarshal().json(Type.class) with camel-jackson
Private CA or mutual TLSsslContextParameters

The traps to remember are the method rule, where a query string turns a POST into a GET and drops the body, the headers that leak into requests and URLs, and the three-minute default timeouts. To expose HTTP endpoints from Camel instead of calling them, see the Camel REST DSL page.