Camel Components

Netty HTTP

Since Camel 2.14

Both producer and consumer are supported

The Netty HTTP component is an extension to Netty component to simplify HTTP transport with Netty.

Stream

Netty HTTP reads the entire request into memory using io.netty.handler.codec.http.HttpObjectAggregator to build the entire full http message. The consumer gives the request body as a Camel stream cache, which can be read multiple times, and the producer gives the response body as a byte array.

With disableStreamCache=true the body is the raw Netty ByteBuf instead (or an InputStream for a chunked message), which you can only read once. If you find a situation where the message body then appears to be empty, or you need to access the data multiple times (eg: doing multicasting, or redelivery error handling), convert the message body to a String or a byte[] which is safe to be re-read multiple times.

On the consumer, the body of a chunked request is an InputStream only when the route runs on the executor service (usingExecutorService=true, the default), as the body cannot be received while the route waits for it on the I/O thread; otherwise the request is aggregated as any other. The stream is closed when the exchange is done, and the part of the body that the route did not read is discarded. When the reply is streamed (its body is an InputStream), the stream is closed once the reply is written instead, as the reply may read it (the request body sent back, as it is or in another stream); such a reply reads it on the I/O thread, so the body must be received already.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-netty-http</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

The URI scheme for a netty component is as follows

netty-http:http://0.0.0.0:8080[?options]

Query parameters vs. endpoint options

You may be wondering how Camel recognizes URI query parameters and endpoint options. For example, you might create endpoint URI as follows: netty-http:http//example.com?myParam=myValue&compression=true . In this example myParam is the HTTP parameter, while compression is the Camel endpoint option. The strategy used by Camel in such situations is to resolve available endpoint options and remove them from the URI. It means that for the discussed example, the HTTP request sent by Netty HTTP producer to the endpoint will look as follows: http//example.com?myParam=myValue, because compression endpoint option will be resolved and removed from the target URL.

Keep also in mind that you cannot specify endpoint options using dynamic headers (like CamelHttpQuery). Endpoint options can be specified only at the endpoint URI definition level (like to or from DSL elements).

A lot more options

This component inherits all the options from Netty, so make sure to look at the Netty documentation as well. Notice that some options from Netty are not applicable when using this Netty HTTP component, such as options related to UDP transport.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Netty HTTP component supports the following options which are listed below.

Name Description Default Type

configuration (common)

The configuration with the default settings of the endpoints that this component creates; each endpoint gets a copy of it.

NettyConfiguration

disconnect (common)

Whether to close the channel after use: the producer closes it when the reply is received (or when the request is written, if sync is false), and the consumer closes it after it writes the reply. The CamelNettyCloseChannelWhenComplete header overrides it per message.

false

boolean

keepAlive (common)

Whether to set the SO_KEEPALIVE socket option on TCP connections (the connections of the producer, and the ones a TCP server accepts), so the operating system sends keep-alive probes on an idle connection and notices a peer that is gone. netty-http also uses it as the default of the Connection header (keep-alive or close).

true

boolean

reuseAddress (common)

Whether to set the SO_REUSEADDR socket option, which allows binding to a local address and port that a previous socket still holds (such as a connection in TIME_WAIT), for example when a server restarts.

true

boolean

reuseChannel (common)

Whether to use the same channel (connection) for the whole processing of an exchange. The producer keeps the channel in the CamelNettyChannel exchange property and uses it again when the same exchange is sent again, for example to call a server several times in one route. The channel goes back to the producer pool when the exchange is done, or is closed if disconnect is true. The consumer stores the channel of the received message in the same exchange property.

false

boolean

sync (common)

Whether the endpoint uses request-reply (true) or one-way (false). With true the producer waits for the reply of the remote server, and the consumer writes the result of the route back as the reply. With false the producer does not wait for a reply, and the consumer sends none.

true

boolean

tcpNoDelay (common)

Whether to set the TCP_NODELAY socket option on TCP connections, which turns off Nagle’s algorithm so small writes are sent at once instead of being combined.

true

boolean

networkInterface (common (advanced))

The name of the network interface (such as eth0) for UDP multicast: a UDP consumer whose host is a multicast address joins the group on it (lo when not set), and the producer sends multicast datagrams through it (IP_MULTICAST_IF).

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

clientMode (consumer)

Whether the consumer connects to the remote host and port as a TCP client, instead of listening as a server, and receives the messages that the remote server sends on that connection. Only used for TCP.

false

boolean

muteException (consumer)

If enabled and an Exchange failed processing on the consumer side the response written back to the remote peer won’t contain the exception’s class, message or stack trace.

true

boolean

reconnect (consumer)

Whether a consumer in clientMode connects again when the connection is closed or cannot be made. If the first connection fails, the consumer then starts without a connection and keeps trying; when false, the consumer fails to start.

true

boolean

reconnectInterval (consumer)

The time in milliseconds that a consumer in clientMode waits before each attempt to connect again.

10000

int

backlog (consumer (advanced))

The maximum number of incoming connections that wait to be accepted by the TCP server (SO_BACKLOG). The operating system may limit it. When 0 (not set), Netty uses the SOMAXCONN value of the operating system.

int

bossCount (consumer (advanced))

The number of threads of the boss EventLoopGroup, which accepts the connections of a TCP server. Not used when bossGroup is set.

1

int

bossGroup (consumer (advanced))

An explicit EventLoopGroup to use as the boss group of a TCP server, which accepts the connections, for example to share it among several consumers. When not set, each consumer creates its own with bossCount threads.

EventLoopGroup

broadcast (consumer (advanced))

Whether to set the SO_BROADCAST socket option on UDP channels, which allows sending datagrams to a broadcast address. Multicast does not need it: a UDP consumer whose host is a multicast address joins that group.

false

boolean

disconnectOnNoReply (consumer (advanced))

Whether the consumer closes the channel when sync is true and there is no reply to write back (the body is null), so the client does not wait for a reply.

true

boolean

executorService (consumer (advanced))

A custom Netty EventExecutorGroup that the consumers of this component use to route the messages when usingExecutorService is true, instead of the one that the component creates.

EventExecutorGroup

maximumPoolSize (consumer (advanced))

The number of threads of the EventExecutorGroup that the consumers of this component use to route the messages (see usingExecutorService). The group has at least one thread more than the Netty default event loop size (twice the number of CPU cores, or the io.netty.eventLoopThreads system property), so a smaller value has no effect. Not used when executorService is set.

int

nettyServerBootstrapFactory (consumer (advanced))

A custom NettyServerBootstrapFactory that the consumer starts instead of creating its own server bootstrap. The consumer does not initialize it, and serverInitializerFactory is then not used. Not used by netty-http.

NettyServerBootstrapFactory

serverClosedChannelExceptionCaughtLogLevel (consumer (advanced))

If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

DEBUG

LoggingLevel

serverExceptionCaughtLogLevel (consumer (advanced))

The logging level at which the consumer logs the exceptions it catches, other than a java.nio.channels.ClosedChannelException (see serverClosedChannelExceptionCaughtLogLevel).

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

WARN

LoggingLevel

serverInitializerFactory (consumer (advanced))

A custom ServerInitializerFactory that builds the channel pipeline (handlers, encoders and decoders) of the consumer, instead of the default one. Not used by netty-http.

ServerInitializerFactory

usingExecutorService (consumer (advanced))

Whether the consumer routes the messages on the threads of the EventExecutorGroup of the component (see maximumPoolSize and executorService), which keeps the messages of a channel in order and keeps the Netty event loop free when the route blocks. When false, the messages are routed on the Netty worker (event loop) threads.

true

boolean

connectTimeout (producer)

The time in milliseconds to wait for a TCP connection to the remote server to be established (the Netty CONNECT_TIMEOUT_MILLIS option), used by the producer and by a consumer in clientMode. 0 means no timeout.

10000

int

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

requestTimeout (producer)

The time in milliseconds that the producer waits for the reply of the remote server. It uses Netty’s ReadTimeoutHandler: the exchange fails with a ReadTimeoutException when no data is read on the channel within this time. 0 (the default) means no timeout. The CamelNettyRequestTimeout header overrides it per message.

long

clientInitializerFactory (producer (advanced))

A custom ClientInitializerFactory that builds the channel pipeline (handlers, encoders and decoders) of the producer, instead of the default one.

ClientInitializerFactory

correlationManager (producer (advanced))

A custom NettyCamelStateCorrelationManager that matches each reply to its request, needed to send several requests concurrently over one channel (producerPoolEnabled=false): the requests and replies must carry a correlation id. Extending TimeoutCorrelationManagerSupport adds the handling of timeouts.

NettyCamelStateCorrelationManager

lazyChannelCreation (producer (advanced))

Whether the producer opens its first connection when the first message is sent (true), or when it starts (false). With false, the producer fails to start when the remote server cannot be reached.

true

boolean

producerPoolBlockWhenExhausted (producer (advanced))

Whether the producer waits for a free channel when the producer pool has producerPoolMaxTotal channels in use (true), or fails at once with a NoSuchElementException (false). producerPoolMaxWait sets how long it waits.

true

boolean

producerPoolEnabled (producer (advanced))

Whether the producer uses a pool of channels, one channel for each request in flight (true), or a single shared channel for all requests (false). With a shared channel and request-reply, the replies can come back out of order: you then need a correlationManager that matches each reply to its request by a correlation id in both messages.

true

boolean

producerPoolMaxIdle (producer (advanced))

The maximum number of idle channels that the producer pool keeps; a channel given back to a full pool is closed. A negative value means no limit.

100

int

producerPoolMaxTotal (producer (advanced))

The maximum number of channels (connections) in the producer pool, in use or idle. A negative value means no limit. Do not set it too low (such as 1): the pool needs room for a new channel, for example when a retry happens, and with producerPoolBlockWhenExhausted=true (the default) the producer then waits for a free channel, which can make the application hang.

-1

int

producerPoolMaxWait (producer (advanced))

The maximum time in milliseconds that the producer waits for a free channel when the producer pool is exhausted and producerPoolBlockWhenExhausted is true; it then fails with a NoSuchElementException. A negative value waits forever, and 0 fails at once.

-1

long

producerPoolMinEvictableIdle (producer (advanced))

The time in milliseconds that a channel must be idle in the producer pool before the pool closes it (the pool checks every 30 seconds). 0 or a negative value keeps idle channels open.

300000

long

producerPoolMinIdle (producer (advanced))

The minimum number of idle channels that the producer pool keeps: every 30 seconds, the pool opens new connections to the remote server to keep this many. 0 keeps none.

int

udpConnectionlessSending (producer (advanced))

Whether the UDP producer sends from an unconnected channel (fire and forget). A channel connected to the remote host and port (false) gets a PortUnreachableException when nothing listens on the remote port.

false

boolean

useByteBuf (producer (advanced))

Whether to convert the message body to a Netty ByteBuf (with the type converters) before writing it: the request of the producer, and the reply of the consumer. The exchange fails when the body cannot be converted.

false

boolean

allowSerializedHeaders (advanced)

Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

channelGroup (advanced)

An explicit Netty ChannelGroup in which a TCP server (consumer) or the producer keeps its open channels, and closes them when it stops. When not set, each creates its own.

ChannelGroup

headerFilterStrategy (advanced)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers.

HeaderFilterStrategy

nativeTransport (advanced)

Whether to use a Netty native transport (epoll on Linux, kqueue on macOS and BSD) instead of NIO. The netty-transport-native-epoll or netty-transport-native-kqueue JAR for the operating system must be on the classpath; the endpoint fails to start when neither transport is available.

false

boolean

nettyHttpBinding (advanced)

To use a custom org.apache.camel.component.netty.http.NettyHttpBinding for binding to/from Netty and Camel Message API.

NettyHttpBinding

noReplyLogLevel (advanced)

The logging level to use when there is nothing to send: on the consumer (if sync is enabled) when there is no reply to send back, and on the producer when the message has no body.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

WARN

LoggingLevel

options (advanced)

Additional Netty channel options, each set with the option. prefix and the name of a Netty ChannelOption constant, for example option.SO_LINGER=5. Only channel options with a boolean or integer value (such as SO_LINGER, SO_TIMEOUT, IP_TOS, IP_MULTICAST_TTL or WRITE_SPIN_COUNT) are recognized; other names are ignored. The producer sets them on the channels it opens (it skips the child. options). The consumer passes the values to Netty as text, which Netty rejects for these options, so the consumer fails to start. This is a multi-value option with prefix: option.

Map

receiveBufferSize (advanced)

The size in bytes of the socket receive buffer (SO_RCVBUF). Only used for UDP.

65536

int

receiveBufferSizePredictor (advanced)

The size in bytes of the buffer that a UDP consumer allocates for each read (a Netty FixedRecvByteBufAllocator), which is the largest datagram it receives in full. When not set, Netty’s default of 2048 bytes applies. Only used by the UDP consumer.

int

sendBufferSize (advanced)

The size in bytes of the socket send buffer (SO_SNDBUF). Only used for UDP.

65536

int

shutdownTimeout (advanced)

The maximum time in milliseconds that a stopping TCP consumer waits for its channels to close and for each of its thread pools to shut down. It continues after that time without waiting further.

100

int

transferExchange (advanced)

Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. The connection headers (CamelNettyRemoteAddress, CamelNettyLocalAddress, CamelNettyChannelHandlerContext, CamelNettySSLSession and the CamelNettySSLClientCert headers) and the CamelNettyRemoteAddress and CamelNettyChannel exchange properties are always the ones of the receiving side: the connection it accepted is the source of truth, and these values are never taken from the transferred exchange.

false

boolean

udpByteArrayCodec (advanced)

Whether the default codec of a UDP endpoint sends and receives the datagram content as a byte array instead of a String. Only used for UDP, when textline is false and no encoders and decoders are set.

false

boolean

unixDomainSocketPath (advanced)

The path of a Unix domain socket that the TCP server (consumer) or the producer uses instead of a TCP socket. Host and port are still required, but are not used. Requires nativeTransport=true, and is not used with clientMode or UDP.

String

workerCount (advanced)

The number of threads of the worker EventLoopGroup, which does the I/O of the channels. When 0 (not set), Netty’s default applies: twice the number of CPU cores, or the value of the io.netty.eventLoopThreads system property. Not used when workerGroup is set.

int

workerGroup (advanced)

An explicit EventLoopGroup to use as the worker group, which does the I/O of the channels, for example to share it among several consumers and producers. When not set, each consumer and producer creates its own with workerCount threads.

EventLoopGroup

allowDefaultCodec (codec)

Whether to install the default codec (a String codec, or the textline or UDP byte array codec) when no encoders and decoders are set. When false, no codec is installed and the messages are Netty ByteBuf.

true

boolean

autoAppendDelimiter (codec)

Whether or not to auto append missing end delimiter when sending using the textline codec.

true

boolean

decoderMaxLineLength (codec)

The maximum length in bytes of a line that the textline codec decodes. A longer line is dropped and fails with a Netty TooLongFrameException.

1024

int

decoders (codec)

The decoders (Netty ChannelHandler) to add to the channel pipeline, as a comma-separated list of references to beans in the registry, each prefixed with #.

String

delimiter (codec)

The delimiter of the textline codec: LINE (a line break, LF or CR LF) or NULL (a null byte).

Enum values:

  • LINE

  • NULL

LINE

TextLineDelimiter

encoders (codec)

The encoders (Netty ChannelHandler) to add to the channel pipeline, as a comma-separated list of references to beans in the registry, each prefixed with #.

String

encoding (codec)

The charset (such as UTF-8 or ISO-8859-1) of the String codec that Camel installs (the textline codec or the default String codec). UTF-8 when not set. When set, it is also set as the charset of the exchanges (the CamelCharsetName exchange property).

String

textline (codec)

Whether to use the text line codec when no encoders and decoders are set: each message is a line of text that ends with the delimiter, and the body is converted to a String before it is sent. When false, the default codec is a String codec without framing, so over TCP each read from the socket becomes one message.

false

boolean

enabledProtocols (security)

The SSL/TLS protocols to enable, as a comma-separated list. Not used when sslContextParameters is set.

TLSv1.2,TLSv1.3

String

hostnameVerification (security)

To enable/disable hostname verification on SSLEngine.

false

boolean

keyStoreFormat (security)

The type of the keystore and the truststore, such as JKS or PKCS12. Defaults to JKS if not set.

String

keyStoreResource (security)

The keystore with the key and certificate of this endpoint, used when ssl is true and sslContextParameters is not set. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.

String

needClientAuth (security)

Configures whether the server needs client authentication when using SSL.

false

boolean

passphrase (security)

Password to use for the keyStore and trustStore. The same password must be configured for both resources.

String

securityConfiguration (security)

Refers to a org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration for configuring secure web resources.

NettyHttpSecurityConfiguration

securityProvider (security)

The algorithm of the KeyManagerFactory and the TrustManagerFactory, such as SunX509 or PKIX. Defaults to SunX509 if not set.

String

ssl (security)

Whether to use SSL/TLS on the connections of this endpoint.

false

boolean

sslClientCertHeaders (security)

When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range.

false

boolean

sslContextParameters (security)

The SSLContextParameters that configure SSL/TLS when ssl is true.

SSLContextParameters

sslHandler (security)

A custom Netty SslHandler to use when ssl is true, instead of the one that Camel creates.

SslHandler

trustStoreResource (security)

The truststore with the certificates that this endpoint trusts, used when ssl is true and sslContextParameters is not set. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.

String

useGlobalSslContextParameters (security)

Enable usage of global SSL context parameters.

false

boolean

Endpoint Options

The Netty HTTP endpoint is configured using URI syntax:

netty-http:protocol://host:port/path

With the following path and query parameters:

Path Parameters

Name Description Default Type

protocol (common)

Required The protocol to use: http, https (which turns on the ssl option), or proxy for a consumer that acts as an HTTP proxy server (consumer only).

Enum values:

  • http

  • https

  • proxy

String

host (common)

Required The local hostname such as localhost, or 0.0.0.0 when being a consumer. The remote HTTP server hostname when using producer.

String

port (common)

The port number. If not set, 80 is used for http, 443 for https and 3128 for proxy.

int

path (common)

The context path of the endpoint, such as /foo. The consumer receives the requests to this path, and the producer sends its requests to it.

String

Query Parameters

Name Description Default Type

bridgeEndpoint (common)

Whether the endpoint is used as a bridge between HTTP endpoints, such as in a proxy route. The producer then does not send the Host header, nor the message headers that repeat the query parameters of the CamelHttpQuery header. The consumer does not map the fields of a form POST to headers, and sets the exchange properties that tell a later camel-http producer to skip the gzip and form encoding of the body. Set throwExceptionOnFailure to false as well, to send back every response as it is.

false

boolean

disconnect (common)

Whether to close the channel after use: the producer closes it when the reply is received (or when the request is written, if sync is false), and the consumer closes it after it writes the reply. The CamelNettyCloseChannelWhenComplete header overrides it per message.

false

boolean

keepAlive (common)

Whether to set the SO_KEEPALIVE socket option on TCP connections (the connections of the producer, and the ones a TCP server accepts), so the operating system sends keep-alive probes on an idle connection and notices a peer that is gone. netty-http also uses it as the default of the Connection header (keep-alive or close).

true

boolean

reuseAddress (common)

Whether to set the SO_REUSEADDR socket option, which allows binding to a local address and port that a previous socket still holds (such as a connection in TIME_WAIT), for example when a server restarts.

true

boolean

reuseChannel (common)

Whether to use the same channel (connection) for the whole processing of an exchange. The producer keeps the channel in the CamelNettyChannel exchange property and uses it again when the same exchange is sent again, for example to call a server several times in one route. The channel goes back to the producer pool when the exchange is done, or is closed if disconnect is true. The consumer stores the channel of the received message in the same exchange property.

false

boolean

sync (common)

Whether the endpoint uses request-reply (true) or one-way (false). With true the producer waits for the reply of the remote server, and the consumer writes the result of the route back as the reply. With false the producer does not wait for a reply, and the consumer sends none.

true

boolean

tcpNoDelay (common)

Whether to set the TCP_NODELAY socket option on TCP connections, which turns off Nagle’s algorithm so small writes are sent at once instead of being combined.

true

boolean

matchOnUriPrefix (consumer)

Whether or not Camel should try to find a target consumer by matching the URI prefix if no exact match is found.

false

boolean

muteException (consumer)

If enabled and an Exchange failed processing on the consumer side the response written back to the remote peer won’t contain the exception’s class, message or stack trace.

true

boolean

send503whenSuspended (consumer)

Whether to answer with HTTP status code 503 (Service Unavailable) while the consumer is suspended. If false, the consumer is removed from the server while it is suspended, and the server stops listening on the port when no other consumer uses it.

true

boolean

backlog (consumer (advanced))

The maximum number of incoming connections that wait to be accepted by the TCP server (SO_BACKLOG). The operating system may limit it. When 0 (not set), Netty uses the SOMAXCONN value of the operating system.

int

bootstrapConfiguration (consumer (advanced))

A NettyServerBootstrapConfiguration bean, such as #myBean, whose options are copied into the configuration of this endpoint. It applies only when it is given in the endpoint URI.

NettyServerBootstrapConfiguration

bossCount (consumer (advanced))

The number of threads of the boss EventLoopGroup, which accepts the connections of a TCP server. Not used when bossGroup is set.

1

int

bossGroup (consumer (advanced))

An explicit EventLoopGroup to use as the boss group of a TCP server, which accepts the connections, for example to share it among several consumers. When not set, each consumer creates its own with bossCount threads.

EventLoopGroup

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

chunkedMaxContentLength (consumer (advanced))

The maximum length in bytes of the content of a received HTTP message, whether it is sent in one piece or in chunks, which the Netty HttpObjectAggregator collects into one message. Applies to the requests of the consumer and the responses of the producer.

1048576

int

compression (consumer (advanced))

Whether the consumer compresses the response body with the Netty HttpContentCompressor, in an encoding that the client accepts in its Accept-Encoding header: gzip, deflate or snappy, or brotli and zstd when their libraries are on the classpath.

false

boolean

disconnectOnNoReply (consumer (advanced))

Whether the consumer closes the channel when sync is true and there is no reply to write back (the body is null), so the client does not wait for a reply.

true

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

httpMethodRestrict (consumer (advanced))

The HTTP methods that the consumer accepts, separated by comma, such as GET,POST. Other methods are answered with HTTP status code 405 (Method Not Allowed), and OPTIONS with the methods that are allowed. By default all methods are accepted.

String

logWarnOnBadRequest (consumer (advanced))

Whether Netty HTTP server should log a WARN if decoding the HTTP request failed and a HTTP Status 400 (bad request) is returned.

true

boolean

mapHeaders (consumer (advanced))

Whether to map the HTTP headers to message headers: those of the request on the consumer, with its query parameters and form fields, and those of the response on the producer. When disabled, the Camel headers such as CamelHttpMethod and CamelHttpResponseCode are not set either, and the Netty HttpRequest or HttpResponse is available from the NettyHttpMessage with getHttpRequest() or getHttpResponse().

true

boolean

maxChunkSize (consumer (advanced))

The maximum length of the content or each chunk. If the content length (or the length of each chunk) exceeds this value, the content or chunk will be split into multiple io.netty.handler.codec.http.HttpContents whose length is maxChunkSize at maximum. See io.netty.handler.codec.http.HttpObjectDecoder.

8192

int

maxHeaderSize (consumer (advanced))

The maximum length of all headers. If the sum of the length of each header exceeds this value, a io.netty.handler.codec.TooLongFrameException will be raised.

8192

int

maxInitialLineLength (consumer (advanced))

The maximum length of the initial line (e.g. GET / HTTP/1.0 or HTTP/1.0 200 OK) If the length of the initial line exceeds this value, a TooLongFrameException will be raised. See io.netty.handler.codec.http.HttpObjectDecoder.

4096

int

nettyServerBootstrapFactory (consumer (advanced))

A custom NettyServerBootstrapFactory that the consumer starts instead of creating its own server bootstrap. The consumer does not initialize it, and serverInitializerFactory is then not used. Not used by netty-http.

NettyServerBootstrapFactory

nettySharedHttpServer (consumer (advanced))

Deprecated To use a shared Netty HTTP server, so that several applications in one JVM can use the same port. Deprecation note: The shared Netty HTTP server was added for OSGi/Karaf, so that several applications in one JVM could use the same port. Use a netty-http consumer per port, where several routes can use the same port, or the platform-http component.

NettySharedHttpServer

serverClosedChannelExceptionCaughtLogLevel (consumer (advanced))

If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

DEBUG

LoggingLevel

serverExceptionCaughtLogLevel (consumer (advanced))

The logging level at which the consumer logs the exceptions it catches, other than a java.nio.channels.ClosedChannelException (see serverClosedChannelExceptionCaughtLogLevel).

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

WARN

LoggingLevel

serverInitializerFactory (consumer (advanced))

A custom ServerInitializerFactory that builds the channel pipeline (handlers, encoders and decoders) of the consumer, instead of the default one. Not used by netty-http.

ServerInitializerFactory

traceEnabled (consumer (advanced))

Specifies whether to enable HTTP TRACE for this Netty HTTP consumer. By default TRACE is turned off.

false

boolean

urlDecodeHeaders (consumer (advanced))

Whether the consumer URL decodes the values it maps to message headers, such as %20 to a space: the values of the HTTP headers and query parameters, and the names and values of the fields of a form POST. The Content-Type header is not decoded. A custom nettyHttpBinding must apply this option itself.

false

boolean

usingExecutorService (consumer (advanced))

Whether the consumer routes the messages on the threads of the EventExecutorGroup of the component (see maximumPoolSize and executorService), which keeps the messages of a channel in order and keeps the Netty event loop free when the route blocks. When false, the messages are routed on the Netty worker (event loop) threads.

true

boolean

connectTimeout (producer)

The time in milliseconds to wait for a TCP connection to the remote server to be established (the Netty CONNECT_TIMEOUT_MILLIS option), used by the producer and by a consumer in clientMode. 0 means no timeout.

10000

int

cookieHandler (producer)

A cookie handler that keeps the cookies of an HTTP session: the producer stores the cookies of each response, and sends them with the next requests.

CookieHandler

requestTimeout (producer)

The time in milliseconds that the producer waits for the reply of the remote server. It uses Netty’s ReadTimeoutHandler: the exchange fails with a ReadTimeoutException when no data is read on the channel within this time. 0 (the default) means no timeout. The CamelNettyRequestTimeout header overrides it per message.

long

throwExceptionOnFailure (producer)

Whether the producer throws a NettyHttpOperationFailedException when the status code of the response is not in okStatusCodeRange. Set to false to get every response as the message, whatever its status code.

true

boolean

clientInitializerFactory (producer (advanced))

A custom ClientInitializerFactory that builds the channel pipeline (handlers, encoders and decoders) of the producer, instead of the default one.

ClientInitializerFactory

lazyChannelCreation (producer (advanced))

Whether the producer opens its first connection when the first message is sent (true), or when it starts (false). With false, the producer fails to start when the remote server cannot be reached.

true

boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

okStatusCodeRange (producer (advanced))

The status codes which are considered a success response. The values are inclusive. Multiple ranges can be defined, separated by comma, e.g. 200-204,209,301-304. Each range must be a single number or from-to with the dash included. The default range is 200-299.

200-299

String

producerPoolBlockWhenExhausted (producer (advanced))

Whether the producer waits for a free channel when the producer pool has producerPoolMaxTotal channels in use (true), or fails at once with a NoSuchElementException (false). producerPoolMaxWait sets how long it waits.

true

boolean

producerPoolEnabled (producer (advanced))

Whether the producer uses a pool of channels, one channel for each request in flight (true), or a single shared channel for all requests (false). With a shared channel and request-reply, the replies can come back out of order: you then need a correlationManager that matches each reply to its request by a correlation id in both messages.

true

boolean

producerPoolMaxIdle (producer (advanced))

The maximum number of idle channels that the producer pool keeps; a channel given back to a full pool is closed. A negative value means no limit.

100

int

producerPoolMaxTotal (producer (advanced))

The maximum number of channels (connections) in the producer pool, in use or idle. A negative value means no limit. Do not set it too low (such as 1): the pool needs room for a new channel, for example when a retry happens, and with producerPoolBlockWhenExhausted=true (the default) the producer then waits for a free channel, which can make the application hang.

-1

int

producerPoolMaxWait (producer (advanced))

The maximum time in milliseconds that the producer waits for a free channel when the producer pool is exhausted and producerPoolBlockWhenExhausted is true; it then fails with a NoSuchElementException. A negative value waits forever, and 0 fails at once.

-1

long

producerPoolMinEvictableIdle (producer (advanced))

The time in milliseconds that a channel must be idle in the producer pool before the pool closes it (the pool checks every 30 seconds). 0 or a negative value keeps idle channels open.

300000

long

producerPoolMinIdle (producer (advanced))

The minimum number of idle channels that the producer pool keeps: every 30 seconds, the pool opens new connections to the remote server to keep this many. 0 keeps none.

int

useRelativePath (producer (advanced))

Whether the producer sends the request target as the path and query only, such as /foo?a=b, instead of the absolute URL.

true

boolean

allowSerializedHeaders (advanced)

Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level.

false

boolean

channelGroup (advanced)

An explicit Netty ChannelGroup in which a TCP server (consumer) or the producer keeps its open channels, and closes them when it stops. When not set, each creates its own.

ChannelGroup

configuration (advanced)

To use a custom configured NettyHttpConfiguration for configuring this endpoint.

NettyHttpConfiguration

disableStreamCache (advanced)

Whether to keep the body as the raw Netty ByteBuf (or as an InputStream for a chunked message), instead of reading it into a stream cache (consumer) or a byte array (producer). The raw body can be read only once, and it is released when the exchange is done. When enabled, an InputStream body is also sent as a chunked request (producer) or reply (consumer).

false

boolean

headerFilterStrategy (advanced)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers.

HeaderFilterStrategy

nativeTransport (advanced)

Whether to use a Netty native transport (epoll on Linux, kqueue on macOS and BSD) instead of NIO. The netty-transport-native-epoll or netty-transport-native-kqueue JAR for the operating system must be on the classpath; the endpoint fails to start when neither transport is available.

false

boolean

nettyHttpBinding (advanced)

To use a custom org.apache.camel.component.netty.http.NettyHttpBinding for binding to/from Netty and Camel Message API.

NettyHttpBinding

noReplyLogLevel (advanced)

The logging level to use when there is nothing to send: on the consumer (if sync is enabled) when there is no reply to send back, and on the producer when the message has no body.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

WARN

LoggingLevel

options (advanced)

Additional Netty channel options, each set with the option. prefix and the name of a Netty ChannelOption constant, for example option.SO_LINGER=5. Only channel options with a boolean or integer value (such as SO_LINGER, SO_TIMEOUT, IP_TOS, IP_MULTICAST_TTL or WRITE_SPIN_COUNT) are recognized; other names are ignored. The producer sets them on the channels it opens (it skips the child. options). The consumer passes the values to Netty as text, which Netty rejects for these options, so the consumer fails to start. This is a multi-value option with prefix: option.

Map

receiveBufferSize (advanced)

The size in bytes of the socket receive buffer (SO_RCVBUF). Only used for UDP.

65536

int

receiveBufferSizePredictor (advanced)

The size in bytes of the buffer that a UDP consumer allocates for each read (a Netty FixedRecvByteBufAllocator), which is the largest datagram it receives in full. When not set, Netty’s default of 2048 bytes applies. Only used by the UDP consumer.

int

sendBufferSize (advanced)

The size in bytes of the socket send buffer (SO_SNDBUF). Only used for UDP.

65536

int

shutdownTimeout (advanced)

The maximum time in milliseconds that a stopping TCP consumer waits for its channels to close and for each of its thread pools to shut down. It continues after that time without waiting further.

100

int

synchronous (advanced)

Whether the producer processes the exchange synchronously: the calling thread waits for the response, instead of the routing continuing asynchronously when the response arrives.

false

boolean

transferException (advanced)

If enabled and an exchange failed processing on the consumer side, the exception is sent back serialized in the response, with the content type application/x-java-serialized-object (only when muteException is false). On the producer side, such a response is deserialized and the exception is thrown as is, instead of the NettyHttpOperationFailedException. The exception must be serializable. This is turned off by default. If you enable it, be aware that Java deserializes the data of the response, which can be a potential security risk.

false

boolean

transferExchange (advanced)

Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. The connection headers (CamelNettyRemoteAddress, CamelNettyLocalAddress, CamelNettyChannelHandlerContext, CamelNettySSLSession and the CamelNettySSLClientCert headers) and the CamelNettyRemoteAddress and CamelNettyChannel exchange properties are always the ones of the receiving side: the connection it accepted is the source of truth, and these values are never taken from the transferred exchange.

false

boolean

unixDomainSocketPath (advanced)

The path of a Unix domain socket that the TCP server (consumer) or the producer uses instead of a TCP socket. Host and port are still required, but are not used. Requires nativeTransport=true, and is not used with clientMode or UDP.

String

workerCount (advanced)

The number of threads of the worker EventLoopGroup, which does the I/O of the channels. When 0 (not set), Netty’s default applies: twice the number of CPU cores, or the value of the io.netty.eventLoopThreads system property. Not used when workerGroup is set.

int

workerGroup (advanced)

An explicit EventLoopGroup to use as the worker group, which does the I/O of the channels, for example to share it among several consumers and producers. When not set, each consumer and producer creates its own with workerCount threads.

EventLoopGroup

decoders (codec)

The decoders (Netty ChannelHandler) to add to the channel pipeline, as a comma-separated list of references to beans in the registry, each prefixed with #.

String

encoders (codec)

The encoders (Netty ChannelHandler) to add to the channel pipeline, as a comma-separated list of references to beans in the registry, each prefixed with #.

String

deserializationFilter (security)

Sets an ObjectInputFilter pattern (jdk.serialFilter syntax) applied when deserializing Java objects from HTTP responses with Content-Type application/x-java-serialized-object. This is used when transferException is enabled and the remote side returns a serialized exception. When not set, the filter configured via the JVM system property jdk.serialFilter is used when present; otherwise a conservative default filter denying java.net. and otherwise allowing java., javax. and org.apache.camel. packages is applied.

String

enabledProtocols (security)

The SSL/TLS protocols to enable, as a comma-separated list. Not used when sslContextParameters is set.

TLSv1.2,TLSv1.3

String

hostnameVerification (security)

To enable/disable hostname verification on SSLEngine.

false

boolean

keyStoreFormat (security)

The type of the keystore and the truststore, such as JKS or PKCS12. Defaults to JKS if not set.

String

keyStoreResource (security)

The keystore with the key and certificate of this endpoint, used when ssl is true and sslContextParameters is not set. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.

String

needClientAuth (security)

Configures whether the server needs client authentication when using SSL.

false

boolean

oauthProfile (security)

OAuth profile name for validating incoming Authorization: Bearer tokens. When set, the request is authenticated before the route is processed. This requires an OAuthTokenValidationFactory; camel-oauth provides the default implementation. Requires usingExecutorService=true and sync=true (the defaults), and is not supported with nettySharedHttpServer.

String

passphrase (security)

Password to use for the keyStore and trustStore. The same password must be configured for both resources.

String

securityConfiguration (security)

Refers to a org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration for configuring secure web resources.

NettyHttpSecurityConfiguration

securityOptions (security)

To configure NettyHttpSecurityConfiguration using key/value pairs from the map. This is a multi-value option with prefix: securityConfiguration.

Map

securityProvider (security)

The algorithm of the KeyManagerFactory and the TrustManagerFactory, such as SunX509 or PKIX. Defaults to SunX509 if not set.

String

ssl (security)

Whether to use SSL/TLS on the connections of this endpoint.

false

boolean

sslClientCertHeaders (security)

When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range.

false

boolean

sslContextParameters (security)

The SSLContextParameters that configure SSL/TLS when ssl is true.

SSLContextParameters

sslHandler (security)

A custom Netty SslHandler to use when ssl is true, instead of the one that Camel creates.

SslHandler

trustStoreResource (security)

The truststore with the certificates that this endpoint trusts, used when ssl is true and sslContextParameters is not set. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.

String

Message Headers

The Netty HTTP component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelHttpAuthentication (common)

Constant: HTTP_AUTHENTICATION

If the user was authenticated using HTTP Basic then this header is added with the value Basic.

String

Content-Type (common)

Constant: CONTENT_TYPE

To set the content-type of the HTTP body. For example: text/plain; charset=UTF-8.

String

connection (common)

Constant: CONNECTION

The Connection header of the reply of the consumer: keep-alive, or close to close the channel after the reply is sent. If not set, the keepAlive option decides, unless the request asked to close.

String

CamelNettyCloseChannelWhenComplete (common)

Constant: NETTY_CLOSE_CHANNEL_WHEN_COMPLETE

Whether to close the Netty channel when the exchange is complete.

Boolean

CamelHttpResponseCode (common)

Constant: HTTP_RESPONSE_CODE

The HTTP status code. On the consumer, the status code of the reply: by default 200, 204 when the reply has no body, and 500 when the exchange failed. On the producer, the status code of the response.

Integer

CamelHttpResponseText (producer)

Constant: HTTP_RESPONSE_TEXT

The reason phrase of the HTTP response, such as OK.

String

CamelHttpProtocolVersion (common)

Constant: HTTP_PROTOCOL_VERSION

The HTTP version of the request that the producer sends, such as HTTP/1.0.

HTTP/1.1

String

CamelHttpMethod (common)

Constant: HTTP_METHOD

The HTTP method, such as GET or POST: the method of the received request on the consumer, and the method of the request to send on the producer. If not set, the producer sends POST when the message has a body, and GET otherwise.

GET

String

CamelHttpQuery (common)

Constant: HTTP_QUERY

Any query parameters, such as foo=bar&beer=yes.

String

CamelHttpPath (common)

Constant: HTTP_PATH

The path of the request relative to the path of the endpoint (consumer). On the producer, a path to append to the path of the endpoint, so the same endpoint can call several paths of the same HTTP server.

String

CamelHttpRawQuery (common)

Constant: HTTP_RAW_QUERY

Any query parameters, such as foo=bar&beer=yes. Stored in the raw form, as they arrived to the consumer (i.e. before URL decoding).

String

CamelHttpUrl (common)

Constant: HTTP_URL

The URL including protocol, host and port, etc: http://0.0.0.0:8080/myapp.

String

CamelHttpCharacterEncoding (common)

Constant: HTTP_CHARACTER_ENCODING

The charset from the content-type header.

String

CamelHttpUri (common)

Constant: HTTP_URI

The URI without protocol, host and port, etc: /myapp.

String

CamelHttpScheme (consumer)

Constant: HTTP_SCHEME

The scheme of the request URI, http or https, when the request line has an absolute URI, as the requests to a proxy (httpProxy) have. Otherwise null.

String

CamelHttpHost (consumer)

Constant: HTTP_HOST

The host of the request URI, when the request line has an absolute URI, as the requests to a proxy (httpProxy) have. Otherwise null.

String

CamelHttpPort (consumer)

Constant: HTTP_PORT

The port of the request URI, when the request line has an absolute URI with a port. Otherwise 443 when ssl is enabled or the scheme is https, and 80 otherwise.

Integer

CamelRestHttpUri (producer)

Constant: REST_HTTP_URI

The URI to call, set by the REST producer. It takes precedence over the endpoint URI, and the producer removes the header when it uses it.

String

CamelRestHttpQuery (producer)

Constant: REST_HTTP_QUERY

The query string, set by the REST producer. It takes precedence over CamelHttpRawQuery, CamelHttpQuery and the query of the endpoint URI, and the producer removes the header when it uses it.

String

CamelNettyChannelHandlerContext (common)

Constant: NETTY_CHANNEL_HANDLER_CONTEXT

The Netty ChannelHandlerContext of the channel that received the message.

ChannelHandlerContext

CamelNettyRemoteAddress (common)

Constant: NETTY_REMOTE_ADDRESS

The address of the remote peer of the channel. For UDP, the address of the sender of the datagram.

SocketAddress

CamelNettyLocalAddress (common)

Constant: NETTY_LOCAL_ADDRESS

The local address of the channel that received the message.

SocketAddress

CamelNettySSLSession (common)

Constant: NETTY_SSL_SESSION

The SSLSession of the connection, when ssl is true.

SSLSession

CamelNettySSLClientCertSubjectName (common)

Constant: NETTY_SSL_CLIENT_CERT_SUBJECT_NAME

The subject name of the client certificate, when sslClientCertHeaders is true.

String

CamelNettySSLClientCertIssuerName (common)

Constant: NETTY_SSL_CLIENT_CERT_ISSUER_NAME

The issuer name of the client certificate, when sslClientCertHeaders is true.

String

CamelNettySSLClientCertSerialNumber (common)

Constant: NETTY_SSL_CLIENT_CERT_SERIAL_NO

The serial number of the client certificate, when sslClientCertHeaders is true.

String

CamelNettySSLClientCertNotBefore (common)

Constant: NETTY_SSL_CLIENT_CERT_NOT_BEFORE

The start of the validity period of the client certificate, when sslClientCertHeaders is true.

Date

CamelNettySSLClientCertNotAfter (common)

Constant: NETTY_SSL_CLIENT_CERT_NOT_AFTER

The end of the validity period of the client certificate, when sslClientCertHeaders is true.

Date

CamelNettyRequestTimeout (common)

Constant: NETTY_REQUEST_TIMEOUT

The request timeout in milliseconds for this message, overriding the requestTimeout option of the producer.

Long

CamelNettyChannel (common)

Constant: NETTY_CHANNEL

The Netty Channel that is used again for the exchange when reuseChannel is true. It is set as an exchange property, not as a header.

Channel

Message Body

The message body at each side of the Netty HTTP component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

stream (org.apache.camel.component.netty.http.NettyChannelBufferStreamCache)

The request body as the stream cache of Camel, which can be read many times; empty for a request without a body, such as a GET. The fields of a form POST are also headers. With disableStreamCache the Netty ByteBuf of the request, or an InputStream for a chunked request, read once.

  • With disableStreamCache=true: pojo or stream

  • With protocol=proxy: pojo (io.netty.buffer.ByteBuf)

Not known when nettyHttpBinding is set.

Consumer reply

null, text, bytes, stream, file or value

The response body: text, bytes, a stream, a file, or a Netty ByteBuf or HttpResponse; no body sends 204. A Map, a List or a POJO is written as its toString(): marshal it first. A failed exchange sends 500 with an empty body (muteException).

Producer input

null, text, bytes, stream or file

The request body: text, bytes, a stream or a file, or a Netty ByteBuf or HttpRequest. A Map, a List or a POJO fails: marshal it first. Without the CamelHttpMethod header, no body sends a GET and a body a POST.

Producer output

bytes (byte[])

The response body as a byte array, empty for a response without a body. With disableStreamCache the Netty ByteBuf of the response, or an InputStream for a chunked response; the ByteBuf is released when the exchange is done.

  • With disableStreamCache=true: pojo or stream

Not known when nettyHttpBinding or sync is set.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

OAuth Bearer token validation

Netty HTTP consumers can validate incoming Authorization: Bearer tokens by setting the oauthProfile endpoint option. The profile is resolved through Camel’s OAuthTokenValidationFactory SPI. The camel-oauth component provides the default implementation for standalone Camel applications; see its documentation for validation profile options and production hardening (expected issuer and audience, HTTPS for JWKS, OIDC discovery, and introspection endpoints). Runtimes can also provide their own implementation.

If oauthProfile is set but no OAuthTokenValidationFactory is available, the route fails to start. Add camel-oauth for the default provider or include a runtime-specific provider from the platform integration.

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:8080/secure?oauthProfile=myprofile")
    .to("direct:businessLogic");
<route>
  <from uri="netty-http:http://0.0.0.0:8080/secure?oauthProfile=myprofile"/>
  <to uri="direct:businessLogic"/>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:8080/secure
      parameters:
        oauthProfile: myprofile
      steps:
        - to:
            uri: direct:businessLogic

When oauthProfile is set, static profile configuration is resolved and validated at route startup. Updates to OAuth profile properties require restarting the route or Camel context before they take effect. Requests without a Bearer token or with an invalid token are rejected with HTTP 401 before the route is processed; missing credentials receive a WWW-Authenticate: Bearer response header and invalid tokens receive WWW-Authenticate: Bearer error="invalid_token". Malformed Authorization headers are rejected with HTTP 400 and WWW-Authenticate: Bearer error="invalid_request". Token validation infrastructure failures are rejected with HTTP 503. For valid tokens, the token validation result is stored on the exchange as the CamelOAuthTokenValidationResult exchange property. The raw Authorization header is removed before the route is invoked.

OAuth validation can perform blocking calls to identity-provider infrastructure during JWKS refresh, OIDC discovery, or token introspection. For this reason, netty-http consumers reject oauthProfile when usingExecutorService=false; keep usingExecutorService=true so validation does not run on a Netty event-loop thread. When several consumers share the same host and port, the first consumer decides the effective pipeline configuration, so a consumer with oauthProfile also fails at startup when another endpoint already initialized the shared server with usingExecutorService=false. The oauthProfile option is not supported with nettySharedHttpServer, because the shared pipeline does not use the endpoint executor service. The oauthProfile option also requires sync=true, which is the default, so token validation rejection responses can be returned to the client.

Automatic OPTIONS handling runs before OAuth validation. OPTIONS requests, including browser CORS preflight requests, are answered with an Allow header without authentication and without invoking the route, unless the endpoint is restricted to the OPTIONS method with httpMethodRestrict. All other HTTP methods are authenticated when oauthProfile is set.

Verifying the host name of the server

Set hostnameVerification=true on a producer that calls an https URL to check that the certificate of the server matches the host it connects to, with the same rules as an HTTPS client: a connection to an IP address needs a certificate that lists that address as a subject alternative name of its own. A certificate that does not match makes the call fail with an SSLHandshakeException.

The option applies to the producer only. On a consumer it is ignored, because the JDK does not support host name verification on the server side of a handshake. To control which clients may connect to a consumer, use client authentication (needClientAuth=true) with a trust store that holds only the certificates you accept.

Access to Netty types

This component uses the org.apache.camel.component.netty.http.NettyHttpMessage as the message implementation on the Exchange. This allows end users to get access to the original Netty request/response instances if needed, as shown below. Mind that the original response may not be accessible at all times.

Java-only: accessing the underlying Netty HTTP request object
io.netty.handler.codec.http.HttpRequest request = exchange.getIn(NettyHttpMessage.class).getHttpRequest();

Using HTTP Basic Authentication

The Netty HTTP consumer supports HTTP basic authentication by specifying the security realm name to use, as shown below

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:{{port}}/foo?securityConfiguration.realm=someRealm")
    .to("direct:secured");
<route>
   <from uri="netty-http:http://0.0.0.0:{{port}}/foo?securityConfiguration.realm=someRealm"/>
   <to uri="direct:secured"/>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:{{port}}/foo
      parameters:
        securityConfiguration.realm: someRealm
      steps:
        - to:
            uri: direct:secured

The realm name is mandatory to enable basic authentication. By default, the JAAS based authenticator is used, which will use the realm name specified (someRealm in the example above) and use the JAAS realm and the JAAS \{{LoginModule}}s of this realm for authentication.

Once the credential of a request has been checked, the Authorization header is removed from the message, so it is not passed on to the route. The CamelHttpAuthentication header is still set to Basic. A request to a resource that the security constraint does not restrict keeps the header as sent.

Specifying ACL on web resources

The org.apache.camel.component.netty.http.SecurityConstraint allows to define constraints on web resources. And the org.apache.camel.component.netty.http.SecurityConstraintMapping is provided out of the box, allowing to easily define inclusions and exclusions with roles.

For example, as shown below in the XML DSL, we define the constraint bean:

  <bean id="constraint" class="org.apache.camel.component.netty.http.SecurityConstraintMapping">
    <!-- inclusions defines url -> roles restrictions -->
    <!-- a * should be used for any role accepted (or even no roles) -->
    <property name="inclusions">
      <map>
        <entry key="/*" value="*"/>
        <entry key="/admin/*" value="admin"/>
        <entry key="/guest/*" value="admin,guest"/>
      </map>
    </property>
    <!-- exclusions is used to define public urls, which requires no authentication -->
    <property name="exclusions">
      <set>
        <value>/public/*</value>
      </set>
    </property>
  </bean>

The constraint above is defined so that

  • access to /* is restricted and any roles are accepted (also if user has no roles)

  • access to /admin/* requires the admin role

  • access to /guest/* requires the admin or guest role

  • access to /public/* is an exclusion that means no authentication is necessary, and is therefore public for everyone without logging in

The roles of an inclusion are a comma-separated list of role names. A user is in role when one of the user roles is equal to one of the listed names. The comparison is case-sensitive, whitespace around each name and blank entries are ignored, and a value of * accepts any role.

To use this constraint, we just need to refer to the bean id as shown below:

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:{{port}}/foo?matchOnUriPrefix=true&securityConfiguration.realm=someRealm&securityConfiguration.securityConstraint=#constraint")
    .to("direct:secured");
<route>
   <from uri="netty-http:http://0.0.0.0:{{port}}/foo?matchOnUriPrefix=true&amp;securityConfiguration.realm=someRealm&amp;securityConfiguration.securityConstraint=#constraint"/>
   <to uri="direct:secured"/>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:{{port}}/foo
      parameters:
        matchOnUriPrefix: true
        securityConfiguration.realm: someRealm
        securityConfiguration.securityConstraint: "#constraint"
      steps:
        - to:
            uri: direct:secured

Examples

In the route below, we use Netty HTTP as an HTTP server, which returns a hardcoded "Bye World" message.

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:8080/foo")
  .transform().constant("Bye World");
<route>
  <from uri="netty-http:http://0.0.0.0:8080/foo"/>
  <transform>
    <constant>Bye World</constant>
  </transform>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:8080/foo
      steps:
        - transform:
            constant: "Bye World"

And we can call this HTTP server using Camel also, with the ProducerTemplate as shown below:

Java-only: ProducerTemplate test API
String out = template.requestBody("netty-http:http://0.0.0.0:8080/foo", "Hello World", String.class);
System.out.println(out);

And we get "Bye World" as the output.

How do I let Netty match wildcards?

By default, Netty HTTP will only match on exact uri’s. But you can instruct Netty to match prefixes. For example

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:8123/foo").to("mock:foo");
<route>
  <from uri="netty-http:http://0.0.0.0:8123/foo"/>
  <to uri="mock:foo"/>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:8123/foo
      steps:
        - to:
            uri: mock:foo

In the route above Netty HTTP will only match if the uri is an exact match, so it will match if you enter
http://0.0.0.0:8123/foo but not match if you do http://0.0.0.0:8123/foo/bar.

So if you want to enable wildcard matching, you do as follows:

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:8123/foo?matchOnUriPrefix=true").to("mock:foo");
<route>
  <from uri="netty-http:http://0.0.0.0:8123/foo?matchOnUriPrefix=true"/>
  <to uri="mock:foo"/>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:8123/foo
      parameters:
        matchOnUriPrefix: true
      steps:
        - to:
            uri: mock:foo

So now Netty matches any endpoints with starts with foo.

To match any endpoint, you can do:

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:8123?matchOnUriPrefix=true").to("mock:foo");
<route>
  <from uri="netty-http:http://0.0.0.0:8123?matchOnUriPrefix=true"/>
  <to uri="mock:foo"/>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:8123
      parameters:
        matchOnUriPrefix: true
      steps:
        - to:
            uri: mock:foo

Using multiple routes with same port

In the same CamelContext you can have multiple routes from Netty HTTP that shares the same port (e.g., a io.netty.bootstrap.ServerBootstrap instance). Doing this requires a number of bootstrap options to be identical in the routes, as the routes will share the same io.netty.bootstrap.ServerBootstrap instance. The instance will be configured with the options from the first route created.

The options the routes must be identical configured is all the options defined in the org.apache.camel.component.netty.NettyServerBootstrapConfiguration configuration class. If you have configured another route with different options, Camel will throw an exception on startup, indicating the options are not identical. To mitigate this ensure all options are identical.

Here is an example with two routes that share the same port.

Two routes sharing the same port

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:{{port}}/foo")
    .to("mock:foo")
    .transform().constant("Bye World");

from("netty-http:http://0.0.0.0:{{port}}/bar")
    .to("mock:bar")
    .transform().constant("Bye Camel");
<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/foo"/>
  <to uri="mock:foo"/>
  <transform>
    <constant>Bye World</constant>
  </transform>
</route>
<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/bar"/>
  <to uri="mock:bar"/>
  <transform>
    <constant>Bye Camel</constant>
  </transform>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:{{port}}/foo
      steps:
        - to:
            uri: mock:foo
        - transform:
            constant: "Bye World"
- route:
    from:
      uri: netty-http:http://0.0.0.0:{{port}}/bar
      steps:
        - to:
            uri: mock:bar
        - transform:
            constant: "Bye Camel"

And here is an example of a mis-configured second route that does not have identical org.apache.camel.component.netty.NettyServerBootstrapConfiguration option as the first route. This will cause Camel to fail on startup.

Two routes are sharing the same port, but the second route is misconfigured and will fail on starting

Java-only: demonstrates a misconfiguration that causes startup failure
from("netty-http:http://0.0.0.0:{{port}}/foo")
  .to("mock:foo")
  .transform().constant("Bye World");

// we cannot have a 2nd route on the same port with SSL enabled, when the 1st route is NOT
from("netty-http:http://0.0.0.0:{{port}}/bar?ssl=true")
  .to("mock:bar")
  .transform().constant("Bye Camel");

Reusing the same server bootstrap configuration with multiple routes

By configuring the common server bootstrap option in a single instance of a org.apache.camel.component.netty.NettyServerBootstrapConfiguration type, we can use the bootstrapConfiguration option on the Netty HTTP consumers to refer and reuse the same options across all consumers.

<bean id="nettyHttpBootstrapOptions" class="org.apache.camel.component.netty.NettyServerBootstrapConfiguration">
  <property name="backlog" value="200"/>
  <property name="connectionTimeout" value="20000"/>
  <property name="workerCount" value="16"/>
</bean>

And in the routes you refer to this option as shown below

  • Java

  • XML

  • YAML

from("netty-http:http://0.0.0.0:{{port}}/foo?bootstrapConfiguration=#nettyHttpBootstrapOptions")
    .to("direct:foo");

from("netty-http:http://0.0.0.0:{{port}}/bar?bootstrapConfiguration=#nettyHttpBootstrapOptions")
    .to("direct:bar");

from("netty-http:http://0.0.0.0:{{port}}/beer?bootstrapConfiguration=#nettyHttpBootstrapOptions")
    .to("direct:beer");
<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/foo?bootstrapConfiguration=#nettyHttpBootstrapOptions"/>
  <to uri="direct:foo"/>
</route>

<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/bar?bootstrapConfiguration=#nettyHttpBootstrapOptions"/>
  <to uri="direct:bar"/>
</route>

<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/beer?bootstrapConfiguration=#nettyHttpBootstrapOptions"/>
  <to uri="direct:beer"/>
</route>
- route:
    from:
      uri: netty-http:http://0.0.0.0:{{port}}/foo
      parameters:
        bootstrapConfiguration: "#nettyHttpBootstrapOptions"
      steps:
        - to:
            uri: direct:foo
- route:
    from:
      uri: netty-http:http://0.0.0.0:{{port}}/bar
      parameters:
        bootstrapConfiguration: "#nettyHttpBootstrapOptions"
      steps:
        - to:
            uri: direct:bar
- route:
    from:
      uri: netty-http:http://0.0.0.0:{{port}}/beer
      parameters:
        bootstrapConfiguration: "#nettyHttpBootstrapOptions"
      steps:
        - to:
            uri: direct:beer

Using a shared Netty HTTP server (deprecated)

The shared Netty HTTP server is deprecated, and will be removed in a future release. This covers the nettySharedHttpServer option and the NettySharedHttpServer, DefaultNettySharedHttpServer, NettySharedHttpServerBootstrapConfiguration and HttpServerSharedInitializerFactory classes.

It was added for OSGi/Karaf, so that several applications (bundles) in one JVM could use the same port. Camel Main, Spring Boot and Quarkus applications run one application per JVM: use a netty-http consumer per port, where several routes can use the same port (see Using multiple routes with same port), or the Platform HTTP component, which uses the HTTP server of the runtime.

A DefaultNettySharedHttpServer is a Netty HTTP server that is configured with a NettySharedHttpServerBootstrapConfiguration and started on its own. The consumers that refer to it with the nettySharedHttpServer option use its port and its pipeline, instead of the server that the component creates. The routes run on the I/O threads of the shared server, so it aggregates each request, also a chunked one, before the route is called (the chunked option of NettySharedHttpServerBootstrapConfiguration is not used).

Implementing a reverse proxy

Netty HTTP component can act as a reverse proxy, in that case Exchange.HTTP_SCHEME, Exchange.HTTP_HOST and Exchange.HTTP_PORT headers are populated from the absolute URL received on the request line of the HTTP request.

Here’s an example of an HTTP proxy that simply transforms the response from the origin server to uppercase.

Java-only: reverse proxy with dynamic toD and Netty response processing
from("netty-http:proxy://0.0.0.0:8080")
    .toD("netty-http:"
        + "${headers." + Exchange.HTTP_SCHEME + "}://"
        + "${headers." + Exchange.HTTP_HOST + "}:"
        + "${headers." + Exchange.HTTP_PORT + "}")
    .process(this::processResponse);

void processResponse(final Exchange exchange) {
    final NettyHttpMessage message = exchange.getIn(NettyHttpMessage.class);
    final FullHttpResponse response = message.getHttpResponse();

    final ByteBuf buf = response.content();
    final String string = buf.toString(StandardCharsets.UTF_8);

    buf.resetWriterIndex();
    ByteBufUtil.writeUtf8(buf, string.toUpperCase(Locale.US));
}