Netty HTTP
Since Camel 2.14
Both producer and consumer are supported
| Stream Netty HTTP reads the entire request into memory using With On the consumer, the body of a chunked request is an |
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: Keep also in mind that you cannot specify endpoint options using dynamic headers (like |
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,*.yamlfiles, 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.
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 |
|---|---|---|---|
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:
| String | ||
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 | ||
The port number. If not set, 80 is used for http, 443 for https and 3128 for proxy. | int | ||
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
Message Headers
The Netty HTTP component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelHttpAuthentication (common) Constant: | If the user was authenticated using HTTP Basic then this header is added with the value Basic. | String | |
| Constant: | To set the content-type of the HTTP body. For example: text/plain; charset=UTF-8. | String | |
| Constant: | 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: | Whether to close the Netty channel when the exchange is complete. | Boolean | |
CamelHttpResponseCode (common) Constant: | 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: | The reason phrase of the HTTP response, such as OK. | String | |
CamelHttpProtocolVersion (common) Constant: | The HTTP version of the request that the producer sends, such as HTTP/1.0. | HTTP/1.1 | String |
| Constant: | 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 |
| Constant: | Any query parameters, such as foo=bar&beer=yes. | String | |
| Constant: | 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 | |
| Constant: | 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 | |
| Constant: | The URL including protocol, host and port, etc: http://0.0.0.0:8080/myapp. | String | |
CamelHttpCharacterEncoding (common) Constant: | The charset from the content-type header. | String | |
| Constant: | The URI without protocol, host and port, etc: /myapp. | String | |
| Constant: | 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 | |
| Constant: | 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 | |
| Constant: | 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 | |
| Constant: | 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 | |
| Constant: | 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: | The Netty ChannelHandlerContext of the channel that received the message. | ChannelHandlerContext | |
CamelNettyRemoteAddress (common) Constant: | The address of the remote peer of the channel. For UDP, the address of the sender of the datagram. | SocketAddress | |
CamelNettyLocalAddress (common) Constant: | The local address of the channel that received the message. | SocketAddress | |
| Constant: | The SSLSession of the connection, when ssl is true. | SSLSession | |
CamelNettySSLClientCertSubjectName (common) Constant: | The subject name of the client certificate, when sslClientCertHeaders is true. | String | |
CamelNettySSLClientCertIssuerName (common) Constant: | The issuer name of the client certificate, when sslClientCertHeaders is true. | String | |
CamelNettySSLClientCertSerialNumber (common) Constant: | The serial number of the client certificate, when sslClientCertHeaders is true. | String | |
CamelNettySSLClientCertNotBefore (common) Constant: | The start of the validity period of the client certificate, when sslClientCertHeaders is true. | Date | |
CamelNettySSLClientCertNotAfter (common) Constant: | The end of the validity period of the client certificate, when sslClientCertHeaders is true. | Date | |
CamelNettyRequestTimeout (common) Constant: | The request timeout in milliseconds for this message, overriding the requestTimeout option of the producer. | Long | |
| Constant: | 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 |
| 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.
Not known when |
Consumer reply |
| 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 |
| 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 |
| 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.
Not known when |
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 |
-
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 |
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.
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&securityConfiguration.realm=someRealm&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:
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
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 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 |
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.
toD and Netty response processingfrom("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));
}