HTTP
Since Camel 2.3
Only producer is supported
The HTTP component provides HTTP-based endpoints for calling external HTTP resources (as a client to call external servers using HTTP).
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-http</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
http:hostname[:port][/resourceUri][?options]
Will by default use port 80 for HTTP and 443 for HTTPS.
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 HTTP component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
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 | |
Whether to log each HTTP request and response with a LoggingHttpActivityListener, when no httpActivityListener is set. To choose what is logged, set a LoggingHttpActivityListener of your own as httpActivityListener. | false | boolean | |
Whether to ignore the Camel control headers of the message: CamelHttpUri, CamelHttpPath, CamelHttpQuery, CamelHttpRawQuery, CamelRestHttpUri, CamelRestHttpQuery, CamelHttpMethod and CamelHttpProtocolVersion. Such headers, left by a previous HTTP component, would otherwise change the URI or the method of the request. | false | boolean | |
Whether to send none of the message headers as HTTP request headers, for an HTTP service that must not receive custom headers. The Content-Type header is still used for the request body. | false | boolean | |
Whether to not map the HTTP response headers to message headers. The CamelHttpResponseCode and CamelHttpResponseText headers are still set. | false | boolean | |
Whether to add the charset of the CamelCharsetName header or exchange property to the Content-Type of a String message body, when the Content-Type has no charset. The body is encoded with the charset of the Content-Type, or UTF-8. When false, CamelCharsetName is not used. | true | boolean | |
A custom CookieStore for the endpoints that have no cookieStore of their own, instead of a BasicCookieStore (in memory) per endpoint. An endpoint with bridgeEndpoint or a cookieHandler keeps no cookies and does not use it. | CookieStore | ||
Whether to copy the headers of the request message to the response message, except the HTTP protocol headers such as Content-Type and Content-Length; a header of the HTTP response with the same name wins. When false, the response message has only the headers of the HTTP response. | true | boolean | |
Whether HttpClient follows redirect responses (3xx with a Location header) to the new location. By default a redirect is not followed: the redirect response is the result, which fails with HttpOperationFailedException (with the redirect location) when throwExceptionOnFailure is enabled. | false | boolean | |
Autowired A custom HttpActivityListener for the endpoints that have no httpActivityListener of their own. It is called when a request is sent and when its response is received, for example to log the HTTP traffic. | HttpActivityListener | ||
The maximum size in bytes, by its Content-Length, of a response body that is read into a byte array. A larger body, or one without Content-Length, is read into a stream cache. Zero or a negative value always uses the stream cache. With disableStreamCache, the body is always the response stream. | 8192 | int | |
The User-Agent header that HttpClient adds to the requests that do not have one already, for example from a User-Agent message header. | String | ||
Whether to allow Java serialization of a message body with Content-Type application/x-java-serialized-object: a consumer deserializes such a request body and can write a Java object as such a response, and the HTTP producer deserializes such a response body. When not allowed, such a body that is received is dropped (null). This is turned off by default: if you enable it, be aware that Java deserializes the data that the other side sends, which can be a security risk. | false | boolean | |
Whether to disable the authentication cache of HttpClient. After a successful authentication, the cache lets the next requests to the same host send the credentials without waiting for a 401 challenge. The cache is kept in the HTTP context of the request, which camel-http creates for each message, so it lasts for one message (its retries and redirects), unless the httpContext option holds an AuthCache. | false | boolean | |
Whether to disable the automatic retries of HttpClient. By default HttpClient retries a request once: after some I/O errors (such as NoHttpResponseException, but not a timeout) when the method is idempotent, and after a 429 (Too Many Requests) or 503 (Service Unavailable) response, waiting as long as its Retry-After header asks (1 second without it). A long Retry-After can make the request appear to hang. | false | boolean | |
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 | |
A shared HttpClientConnectionManager for all the endpoints of this component, instead of a connection pool per endpoint. The options for the connection pool, the TLS and the sockets (such as maxTotalConnections, connectionsPerRoute, connectionTimeToLive, sslContextParameters, x509HostnameVerifier and soTimeout) are then not applied: configure them on this connection manager. The component closes it when it stops. | HttpClientConnectionManager | ||
The maximum time (in millis) a pooled connection can stay idle and still be reused. A connection idle for longer is closed when it would be reused, and the request opens a new one, whatever Keep-Alive timeout the server announced. Set it below the idle timeout of a NAT, firewall or load balancer that drops idle connections silently: the next request on such a connection would otherwise wait for the read timeout and fail. Zero (the default) or a negative value means no limit. | long | ||
The maximum number of connections to the same route (the scheme, host and port of the target, and the proxy) in the connection pool of an endpoint. | 20 | int | |
Whether to disable the connection state tracking of HttpClient. By default a pooled connection that carries a user identity (the principal of an NTLM authentication or of a TLS client certificate) is reused only by a request with the same identity. camel-http starts each message with a new HTTP context, which has no identity, so such connections are not reused unless this option is enabled. | false | boolean | |
The maximum lifetime (in millis) of a pooled connection, counted from when it was opened, whether busy or idle: an older connection is closed instead of being reused. A negative value (the default) means no limit, and zero means that a connection is never reused. | long | ||
Whether to disable the content compression of HttpClient: it then sends no Accept-Encoding header and does not decompress the response body. The producer still decompresses a gzip body, unless bridgeEndpoint is enabled. | false | boolean | |
Whether to disable the cookie management of HttpClient: it then neither keeps the cookies of the responses nor sends the cookies of the cookie store, and clearExpiredCookies does nothing. A Cookie message header is still sent. | false | boolean | |
Whether HttpClient sends no default User-Agent header (Apache-HttpClient and its version) when the userAgent option is not set. | false | boolean | |
To use a custom HttpBinding for the consumers of this component, which reads the HTTP servlet request into the Camel message and writes the Camel message to the HTTP servlet response. The HTTP producer (camel-http) does not use it. | HttpBinding | ||
The HttpClientConfigurer for the endpoints that have no httpClientConfigurer of their own. It is called with the HttpClientBuilder of the endpoint before the HttpClient is built, for example to configure authentication. | HttpClientConfigurer | ||
A shared HttpConfiguration with default options for the endpoints that this component creates; an option set on the endpoint takes precedence. Only the HTTP producer (camel-http) uses it, and only its authentication options (authMethod, which must be set, with the credentials) configure the HTTP client. The consumer components ignore it. | HttpConfiguration | ||
A custom HttpContext for the endpoints that have no httpContext of their own. Each request runs in a new context that has this one as parent: HttpClient reads attributes from it (such as an AuthCache, a CookieStore or a user token), but the attributes set during a request are not kept in it. | HttpContext | ||
The maximum number of connections in the connection pool of an endpoint (each endpoint has its own pool, unless clientConnectionManager is set). A request that finds no free connection waits up to connectionRequestTimeout. | 200 | int | |
Whether to disable the redirect handling of HttpClient, so that redirects are never followed, even with followRedirects enabled. Without followRedirects, redirects are not followed anyway. | false | boolean | |
Whether HttpClient takes its defaults from the JVM system properties: the proxy (http.proxyHost, https.proxyHost and http.nonProxyHosts, through the default ProxySelector), the User-Agent (http.agent), connection reuse (http.keepAlive), the credentials of the default java.net.Authenticator and, without sslContextParameters, the key store and trust store of the TLS connections (javax.net.ssl.*). | false | boolean | |
The time (in millis) a pooled connection must have been idle before it is checked, prior to its reuse, for having been closed by the server. A request sent on a connection that the server closed fails with NoHttpResponseException, and HttpClient retries it only for idempotent methods. Zero checks the connection before each reuse, at the cost of a read of up to 1 millisecond per request; a negative value disables the check. The check cannot see a connection that a NAT or firewall dropped silently: use connectionIdleTimeout for that. | 2000 | long | |
To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | ||
Comma-separated list of hosts that should bypass the proxy. Supports wildcards, e.g., localhost,.example.com,192.168.. | String | ||
The domain for NTLM authentication with the proxy server (NTLM is deprecated). When set, the proxy credentials are NTLM credentials (NTCredentials). | String | ||
Deprecated Deprecated: use proxyHost. The host name of the HTTP proxy server; when set, it takes precedence over proxyHost. | String | ||
The authentication method for the proxy server: Basic, Digest or NTLM (NTLM is deprecated). camel-http does not use this option: HttpClient uses the method that the proxy asks for in its 407 response, with NTLM credentials (NTCredentials) when proxyAuthDomain is set. Enum values:
| String | ||
The workstation name for NTLM authentication with the proxy server, used together with proxyAuthDomain (NTLM is deprecated). | String | ||
The password for authentication with the proxy server, used together with proxyAuthUsername. | String | ||
Deprecated Deprecated: use proxyPort. The port of the HTTP proxy server; when set, it takes precedence over proxyPort. | Integer | ||
Proxy server connection protocol scheme. Defaults to http regardless of the target endpoint scheme, because most corporate HTTP proxies expect a plain HTTP connection on their listener port. Enum values:
| http | String | |
The username for authentication with the proxy server, used together with proxyAuthPassword. | String | ||
The host name of the HTTP proxy server. A proxy is used only when both proxyHost and proxyPort are set. | String | ||
The port of the HTTP proxy server. | Integer | ||
Sets an ObjectInputFilter pattern (jdk.serialFilter syntax) applied when deserializing Java objects from requests or responses with Content-Type application/x-java-serialized-object (only used when allowJavaSerializedObject or transferException is enabled). When not set, the JVM-wide jdk.serialFilter is used if present; otherwise a default filter is applied that rejects java.net., allows java., javax.* and org.apache.camel.*, and rejects every other class. | String | ||
How the host name in the certificate of the server is verified. CLIENT (the default) uses only x509HostnameVerifier, after the TLS handshake, so a NoopHostnameVerifier turns the check off. BUILTIN uses only the check of the JSSE provider (the JDK), during the handshake, and ignores x509HostnameVerifier. BOTH runs the JSSE check and then x509HostnameVerifier, so a NoopHostnameVerifier cannot turn the check off. BOTH is the safer choice when no custom verifier is needed. Enum values:
| CLIENT | HostnameVerificationPolicy | |
The SSLContextParameters (key store, trust store, protocols and cipher suites) for the TLS connections of the endpoints that have no sslContextParameters of their own. An endpoint that has SSLContextParameters uses https, also when its URI starts with http. | SSLContextParameters | ||
Whether the https endpoints that have no sslContextParameters (and whose component has none) use the global SSLContextParameters of the CamelContext. | false | boolean | |
The HostnameVerifier that checks the host name in the certificate of the server, after the TLS handshake: DefaultHostnameVerifier (the default) or a custom one. NoopHostnameVerifier turns the check off, which is insecure. Not used with hostnameVerificationPolicy BUILTIN. | HostnameVerifier | ||
The time (in millis) to wait for a free connection of the connection pool, when maxTotalConnections or connectionsPerRoute connections are in use; the request then fails with ConnectionRequestTimeoutException. Zero does not wait: the request fails at once when no connection is free. It can be set on the endpoint too. | 180000 | long | |
The time (in millis) to wait until a new connection to the server, or to the proxy, is established, including its TLS handshake. Zero means no timeout. It can be set on the endpoint too. | 180000 | long | |
The socket timeout (in millis) while a request runs, instead of soTimeout: the maximum time to wait for data on a read. Zero (the default) means not set, so soTimeout applies. It can be set on the endpoint too. | long | ||
The socket timeout (SO_TIMEOUT, in millis) of the connections: the maximum time to wait for data on a read, while waiting for the response and while reading it. Zero means no timeout. When responseTimeout is set, it replaces this timeout while a request runs. It can be set on the endpoint too. | 180000 | long |
Endpoint Options
The HTTP endpoint is configured using URI syntax:
http://httpUri
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Whether to turn off the caching of the raw HTTP stream. By default the consumer (camel-servlet, camel-jetty) copies the request body into a stream cache, so it can be read more than once, and the producer (camel-http) does the same with the response body. When true, the message body is the raw input stream, which can only be read once: use it to stream a large payload directly to a file or another store, or in a proxy route that does not read the body. The producer then closes the response stream when the exchange completes. | false | boolean | |
To use a custom HeaderFilterStrategy to filter the headers that are mapped between the Camel message and the HTTP request and response. | HeaderFilterStrategy | ||
If true, the producer ignores the CamelHttpUri header and calls the URL of the endpoint, as a proxy or bridge route needs (the CamelHttpPath and CamelHttpQuery headers still apply). It also sends the request body as is, even with a gzip Content-Encoding, does not send headers that repeat the query parameters, and keeps no cookies. Set throwExceptionOnFailure to false as well to pass every response back to the caller. On a consumer it keeps a gzip request body compressed. | false | boolean | |
Whether to add the Connection: close header to the HTTP request, so the connection is closed after the response instead of being kept for reuse. | false | boolean | |
The HTTP method to use. When set, the CamelHttpMethod header cannot override it. When not set, the CamelHttpMethod header is used, otherwise GET when the URL has a query string or the body is empty, and POST when there is a body. Enum values:
| HttpMethods | ||
Whether to log each HTTP request and response with a LoggingHttpActivityListener, when no httpActivityListener is set. To choose what is logged, set a LoggingHttpActivityListener of your own as httpActivityListener. | false | boolean | |
Whether to send the message body as a multipart/form-data request with a single part, named by multipartUploadName, for example to upload a file. The part is text for a String body and binary otherwise. To send several parts, set an HttpEntity built with org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder as the body, which is sent as it is. | false | boolean | |
The name of the part in the multipart/form-data request when multipartUpload is enabled. | data | String | |
Whether to ignore the Camel control headers of the message: CamelHttpUri, CamelHttpPath, CamelHttpQuery, CamelHttpRawQuery, CamelRestHttpUri, CamelRestHttpQuery, CamelHttpMethod and CamelHttpProtocolVersion. Such headers, left by a previous HTTP component, would otherwise change the URI or the method of the request. | false | boolean | |
Whether to send none of the message headers as HTTP request headers, for an HTTP service that must not receive custom headers. The Content-Type header is still used for the request body. | false | boolean | |
Whether to not map the HTTP response headers to message headers. The CamelHttpResponseCode and CamelHttpResponseText headers are still set. | false | boolean | |
Whether to throw an HttpOperationFailedException when the response has a status code outside okStatusCodeRange. Set it to false to get every response as the message, whatever its status code. | true | boolean | |
Whether to remove the expired cookies from the cookieStore before each request, so that the store does not keep growing. Not done when the component has cookieManagementDisabled or the endpoint has bridgeEndpoint. | true | boolean | |
Whether to add the charset of the CamelCharsetName header or exchange property to the Content-Type of a String message body, when the Content-Type has no charset. The body is encoded with the charset of the Content-Type, or UTF-8. When false, CamelCharsetName is not used. | true | boolean | |
A CookieHandler, such as InstanceCookieHandler or ExchangeCookieHandler, that stores the cookies of the responses and sends them with the next requests, to keep an HTTP session. | CookieHandler | ||
A custom CookieStore that keeps the cookies of the HTTP responses and sends them with the next requests. By default each endpoint has its own BasicCookieStore, in memory, shared by all its messages. With bridgeEndpoint or a cookieHandler, the endpoint keeps no cookies and does not use it. | CookieStore | ||
If true, the headers of the request message are copied to the response message, apart from HTTP protocol headers such as Content-Encoding and Location, and without overriding the headers of the HTTP response. If false, the response message only has the headers of the HTTP response. | true | boolean | |
The value of the Host header of the request, instead of the host and port of the request URI. preserveHostHeader, when the message has a Host header, takes precedence. | String | ||
Whether an HTTP DELETE request sends the message body. By default a DELETE request has no body. | false | boolean | |
Whether HttpClient follows redirect responses (3xx with a Location header) to the new location. By default a redirect is not followed: the redirect response is the result, which fails with HttpOperationFailedException (with the redirect location) when throwExceptionOnFailure is enabled. | false | boolean | |
Whether an HTTP GET request sends the message body. By default a GET request has no body. | false | boolean | |
A custom HttpActivityListener that is called when a request is sent and when its response is received, for example to log the HTTP traffic. It is not called with a custom httpClient. | HttpActivityListener | ||
If true, the producer does not read the response body: the message body is null (also in the HttpOperationFailedException), and only the status code and headers of the response are mapped. | false | boolean | |
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 | |
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. | 200-299 | String | |
If true, the producer sets the Host header of the HTTP request to the value of the Host message header (when there is one). In a reverse proxy, the downstream server then sees the host that the client called, so it can build correct URLs for the proxied service. | false | boolean | |
The User-Agent header that HttpClient adds to the requests that do not have one already, for example from a User-Agent message header. | String | ||
A custom HttpClientBuilder from which the endpoint builds its HttpClient, instead of the builder that the component creates. The settings that the component makes on its builder are then not applied: the httpClient. options, the timeouts other than soTimeout, the *Disabled options, and the redirect handling that is off without followRedirects (HttpClient follows redirects by default). | HttpClientBuilder | ||
A custom HttpClientConnectionManager for this endpoint, instead of the connection pool that the component creates for it. The options for the connection pool, the TLS and the sockets (such as maxTotalConnections, sslContextParameters and soTimeout) are then not applied. The endpoint closes it when it stops. | HttpClientConnectionManager | ||
The maximum number of connections to the same route (the scheme, host and port of the target, and the proxy) in the connection pool of this endpoint, instead of the value of the component. | 20 | int | |
A custom HttpClient for the producer, instead of the one that the endpoint builds. The options that configure the HttpClient (such as the timeouts, the connection pool, TLS, authentication, proxy, cookieStore, oauthProfile and httpActivityListener) are not applied to it. The endpoint closes it when it stops. | HttpClient | ||
A custom HttpClientConfigurer that is called with the HttpClientBuilder of the endpoint before the HttpClient is built, for example to configure authentication. It replaces the httpClientConfigurer of the component; the configuration for the auth, proxy and oauth2 options is still applied. | HttpClientConfigurer | ||
Options of the HttpClient as key/value pairs with the httpClient. prefix, such as httpClient.maxRedirects=5 or httpClient.expectContinueEnabled=true. Each option sets the property of that name on the HttpClientBuilder or, when it has none, on the RequestConfig.Builder. An unknown option fails the creation of the endpoint. This is a multi-value option with prefix: httpClient. | Map | ||
Socket options for the connections of the endpoint as key/value pairs with the httpConnection. prefix, such as httpConnection.tcpNoDelay=true or httpConnection.soKeepAlive=true. Each option sets the property of that name on the SocketConfig.Builder. Not applied with a custom clientConnectionManager. This is a multi-value option with prefix: httpConnection. | Map | ||
A custom HttpContext, instead of the one of the component. Each request runs in a new context that has this one as parent: HttpClient reads attributes from it (such as an AuthCache, a CookieStore or a user token), but the attributes set during a request are not kept in it. | HttpContext | ||
The maximum number of connections in the connection pool of this endpoint, instead of the value of the component. A request that finds no free connection waits up to connectionRequestTimeout. | 200 | int | |
Whether HttpClient takes its defaults from the JVM system properties: the proxy (http.proxyHost, https.proxyHost and http.nonProxyHosts, through the default ProxySelector), the User-Agent (http.agent), connection reuse (http.keepAlive), the credentials of the default java.net.Authenticator and, without sslContextParameters, the key store and trust store of the TLS connections (javax.net.ssl.*). | false | boolean | |
Comma-separated list of hosts that are called directly, not through the proxy. Supports the * wildcard, e.g. localhost,.example.com,192.168.. The matching is case-insensitive. | String | ||
Deprecated The domain for NTLM authentication with the proxy server. Setting it selects NTLM credentials. | String | ||
Deprecated Deprecated: use proxyHost. The host of the proxy server; it takes precedence over proxyHost. | String | ||
The proxy authentication method: Basic, Bearer or NTLM (NTLM is deprecated). This option is not used: the proxy credentials are username and password credentials, or NTLM credentials when proxyAuthDomain is set. Enum values:
| String | ||
Deprecated The workstation name for NTLM authentication with the proxy server. | String | ||
The password for authentication with the proxy server. | String | ||
Deprecated Deprecated: use proxyPort. The port of the proxy server; it takes precedence over proxyPort. | int | ||
Proxy server connection protocol scheme. Defaults to http regardless of the target endpoint scheme, because most corporate HTTP proxies expect a plain HTTP connection on their listener port. Enum values:
| http | String | |
The username for authentication with the proxy server. It is used only together with proxyAuthPassword. | String | ||
The host of the HTTP proxy server. The proxy is used only when proxyPort is set too. | String | ||
The port of the HTTP proxy server. | int | ||
The bearer token for Bearer authentication; it is used only when authMethod is Bearer. | String | ||
Deprecated The domain for NTLM authentication. Setting it also selects NTLM. | String | ||
If this option is true, camel-http sends the Basic credentials or the Bearer token with the first request, without waiting for the server to ask for them with a 401 response. The request fails when no credentials are configured. | false | boolean | |
Deprecated The host that the credentials are offered to, on any port. When not set, they are only offered to the scheme, host and port of the endpoint URL. With NTLM it is also the workstation name. | String | ||
The authentication method: Basic, Bearer or NTLM (NTLM is deprecated). Bearer sends authBearerToken, NTLM uses authUsername, authPassword and authDomain, and otherwise authUsername and authPassword are used as username and password credentials. Unless authenticationPreemptive is enabled, the credentials are only sent when the server asks for them with a 401 response. Enum values:
| String | ||
The password for Basic or NTLM authentication. | String | ||
The username for Basic or NTLM authentication. It is used only together with authPassword. | String | ||
How the host name in the certificate of the server is verified. CLIENT (the default) uses only x509HostnameVerifier, after the TLS handshake, so a NoopHostnameVerifier turns the check off. BUILTIN uses only the check of the JSSE provider (the JDK), during the handshake, and ignores x509HostnameVerifier. BOTH runs the JSSE check and then x509HostnameVerifier, so a NoopHostnameVerifier cannot turn the check off. BOTH is the safer choice when no custom verifier is needed. Enum values:
| CLIENT | HostnameVerificationPolicy | |
Whether to send the OAuth2 client ID and client secret in the body of the token request (client_secret_post) instead of in an HTTP Basic Authorization header (client_secret_basic). | false | boolean | |
How long, in seconds, a cached OAuth2 token stays valid when the token response has no expires_in field. With 0 or less such a token is not cached. | 3600 | long | |
How many seconds before its expiry a cached OAuth2 token is no longer used and a new one is requested, to allow for the time a request takes to reach the server. Raise it when the token endpoint answers slowly or the tokens expire quickly: with a margin too small, the server can reject a token that expired on the way with a 4xx response. | 5 | long | |
How cached OAuth2 tokens are shared between requests when oauth2CacheTokens is enabled. FULL_URI uses one token per request URI including the query, HOST_AND_PATH one per path, and HOST_ONLY one per scheme, host and port. The token request does not depend on the request URI, so HOST_AND_PATH and HOST_ONLY request fewer tokens. Enum values:
| HOST_ONLY | OAuth2CachedTokensKey | |
Whether to cache the OAuth2 access tokens and reuse them until they expire. When false, the producer gets a new token for every request. | false | boolean | |
The OAuth2 client ID. The producer gets an access token from oauth2TokenEndpoint with the client credentials grant, and sends it as a bearer token, only when oauth2ClientId, oauth2ClientSecret and oauth2TokenEndpoint are all set. | String | ||
The OAuth2 client secret. | String | ||
The OAuth2 resource indicator (RFC 8707), sent as the resource parameter of the token request. | String | ||
The OAuth2 scope, sent as the scope parameter of the token request. | String | ||
The URL of the OAuth2 token endpoint, which the producer calls with the client credentials grant to get an access token. | String | ||
The name of a camel-oauth profile to use for outgoing requests. When set, a bearer token is resolved per HTTP request using the named profile (properties under camel.oauth.NAME.*) and injected as an Authorization: Bearer header. Requires camel-oauth on the classpath. The token is only attached to requests directed at the endpoint’s own authority; redirects to a different host or port do not receive it. | String | ||
The SSLContextParameters (key store, trust store, protocols and cipher suites) for the TLS connections of this endpoint, instead of those of the component. With it, the endpoint uses https, also when its URI starts with http. Not applied with a custom clientConnectionManager. | SSLContextParameters | ||
The HostnameVerifier that checks the host name in the certificate of the server, after the TLS handshake, instead of the one of the component (DefaultHostnameVerifier by default). NoopHostnameVerifier turns the check off, which is insecure. Not used with hostnameVerificationPolicy BUILTIN. | HostnameVerifier | ||
To use a custom strategy to compute the key of cached OAuth2 tokens when oauth2CacheTokens is enabled. When set, oauth2CachedTokensKey is not used. | OAuth2CachedTokensKeyResolver |
Message Headers
The HTTP component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The Content-Encoding of the request body: with gzip, the producer compresses a text, byte array or stream body (not with bridgeEndpoint). On the response message, the Content-Encoding of the HTTP response, which is removed when HttpClient has decompressed the body. | String | |
CamelHttpResponseCode (producer) Constant: | The HTTP status code of the response, such as 200. It is also set when the request fails with HttpOperationFailedException. | int | |
CamelHttpResponseText (producer) Constant: | The reason phrase of the HTTP response, such as OK. | String | |
| Constant: | The query string of the request, such as a=1&b=2 (without the ?), instead of the query of the endpoint URI. CamelHttpRawQuery takes precedence over it. A query string makes the method GET, unless the httpMethod option or the CamelHttpMethod header sets it. | String | |
CamelHttpProtocolVersion (producer) Constant: | The HTTP protocol version of the request, such as HTTP/1.0 (HTTP/1.1 by default). | String | |
| Constant: | The Host header of the incoming request. The producer sends it as the Host header of the request only when preserveHostHeader is enabled. | String | |
| Constant: | The URI to call, set by the REST producer. It takes precedence over CamelHttpUri and the endpoint URI (also with bridgeEndpoint), and the producer removes the header when it uses it. | String | |
| Constant: | The URI of the HTTP server to call, instead of the endpoint URI. It is only the address of the server: endpoint options in it, such as security options, are not applied. When the endpoint URI has a query, that query is used instead of the query of this URI. Ignored with bridgeEndpoint. | String | |
| Constant: | A path to append to the path of the endpoint URI (or of CamelHttpUri), before the query. A leading slash is ignored, so the path is always relative to the path of the endpoint URI. | 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 | |
| Constant: | The query string of the request, as for CamelHttpQuery, which this header takes precedence over. Unlike CamelHttpQuery, it does not make the method GET. | String | |
| Constant: | The HTTP method of the request, such as GET or POST, when the httpMethod option is not set. Without both, the method is GET when there is a query string (CamelHttpQuery, or the query of CamelHttpUri or of the endpoint URI) or the message has no body, and POST otherwise. Enum values:
| HttpMethods | |
CamelHttpCharacterEncoding (producer) Constant: | The character encoding of a request received by an HTTP consumer, such as camel-servlet. The camel-http producer does not use it. | String | |
| Constant: | The Content-Type of the request body, such as application/json; charset=UTF-8. On the response message, the Content-Type of the HTTP response. | String |
Message Body
The message body at each side of the 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 |
|---|---|---|
Producer input |
| The request body: text, bytes, a stream or a file. A Map or a List fails: marshal it first. Without httpMethod, no body sends a GET and a body a POST. |
Producer output |
| The response body: a byte array when its Content-Length is at most responsePayloadStreamingThreshold (8192), otherwise the stream cache (the stream itself with disableStreamCache); null for a response without a body. |
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
Which HTTP method will be used
Without the httpMethod option, the message body decides the method: a message with a body is sent as a POST, and a message without a body as a GET. After unmarshal, split or setBody the message has a body, so a call meant as a GET is sent as a POST. Set httpMethod: GET on the endpoint when you mean a GET; a GET sends no body (unless getWithBody is true). |
The method is chosen in this order:
-
The
httpMethodoption of the endpoint. -
The
CamelHttpMethodheader. -
GETwhen theCamelHttpQueryheader, or theCamelHttpUriheader, has a query string. -
GETwhen the endpoint URI has a query string. -
POSTwhen the message has a body. -
GETotherwise.
For example, a stock lookup for each line of an order is a GET, whatever the line in the body is:
-
Java
-
XML
-
YAML
from("direct:checkStock")
.split(simple("${body[lines]}"))
.toD("http://localhost:8080/stock/${body[sku]}?httpMethod=GET")
.log("Stock answer: ${body}")
.end(); <route>
<from uri="direct:checkStock"/>
<split>
<simple>${body[lines]}</simple>
<toD uri="http://localhost:8080/stock/${body[sku]}?httpMethod=GET"/>
<log message="Stock answer: ${body}"/>
</split>
</route> - route:
from:
uri: direct:checkStock
steps:
- split:
expression:
simple:
expression: "${body[lines]}"
steps:
- toD:
uri: "http://localhost:8080/stock/${body[sku]}"
parameters:
httpMethod: GET
- log:
message: "Stock answer: ${body}" To send the order as JSON, marshal the body first, and say that it is a POST:
-
Java
-
XML
-
YAML
from("direct:createOrder")
.marshal().json()
.to("http://localhost:8080/orders?httpMethod=POST"); <route>
<from uri="direct:createOrder"/>
<marshal>
<json/>
</marshal>
<to uri="http://localhost:8080/orders?httpMethod=POST"/>
</route> - route:
from:
uri: direct:createOrder
steps:
- marshal:
json: {}
- to:
uri: http://localhost:8080/orders
parameters:
httpMethod: POST Message Body
Camel will store the HTTP response from the external server on the OUT body. All headers from the IN message will be copied to the OUT message, so headers are preserved during routing. Additionally, Camel will add the HTTP response headers as well to the OUT message headers.
Using System Properties
When setting useSystemProperties to true, the HTTP Client will look for the following System Properties, and it will use it:
-
ssl.TrustManagerFactory.algorithm -
javax.net.ssl.trustStoreType -
javax.net.ssl.trustStore -
javax.net.ssl.trustStoreProvider -
javax.net.ssl.trustStorePassword -
java.home -
ssl.KeyManagerFactory.algorithm -
javax.net.ssl.keyStoreType -
javax.net.ssl.keyStore -
javax.net.ssl.keyStoreProvider -
javax.net.ssl.keyStorePassword -
http.proxyHost -
http.proxyPort -
https.proxyHost -
https.proxyPort -
http.nonProxyHosts -
http.keepAlive
The http.proxyHost and http.proxyPort properties apply to http targets only. For https targets, set https.proxyHost and https.proxyPort.
Without useSystemProperties, the HTTP Client does not read these properties, with one exception: it uses the default trust store of the JVM, so the javax.net.ssl.trustStore properties apply unless sslContextParameters is set.
You can set useSystemProperties on the endpoint, or on the component for all its endpoints, such as with camel.component.http.use-system-properties=true. The https component is configured on its own, such as with camel.component.https.use-system-properties=true.
Response code
Camel will handle, according to the HTTP response code:
-
Response code is in the range 100..299, Camel regards it as a success response.
-
Response code is in the range 300..399, Camel regards it as a redirection response and will throw a
HttpOperationFailedExceptionwith the information. -
Response code is 400+, Camel regards it as an external server failure and will throw a
HttpOperationFailedExceptionwith the information.
throwExceptionOnFailure
The option, throwExceptionOnFailure, can be set to false to prevent the HttpOperationFailedException from being thrown for failed response codes. This allows you to get any response from the remote server.
Handling HTTP 429 Too Many Requests
When a server responds with HTTP 429 (Too Many Requests) and includes a Retry-After header, the underlying Apache HttpClient 5 will automatically wait for the specified duration before retrying the request. If the server returns a long retry delay (for example, Retry-After: 3600 for one hour), the HTTP component will appear to hang for that duration.
To avoid this, you can disable automatic retries on the component:
HttpComponent configurationHttpComponent httpComponent = context.getComponent("https", HttpComponent.class);
httpComponent.setAutomaticRetriesDisabled(true); Or as a URI option on the endpoint:
https://myhost/mypath?automaticRetriesDisabled=true With automatic retries disabled, a 429 response is treated as an error and a HttpOperationFailedException is thrown immediately (unless throwExceptionOnFailure=false).
Exceptions
HttpOperationFailedException exception contains the following information:
-
The HTTP status code
-
The HTTP status line (text of the status code)
-
Redirect location if server returned a redirect
-
Response body as a
java.lang.String, if server provided a body as response
Configuring URI to call
You can set the HTTP producer’s URI directly from the endpoint URI. In the route below, Camel will call out to the external server, oldhost, using HTTP.
-
Java
-
XML
-
YAML
from("direct:start")
.to("http://oldhost"); <route>
<from uri="direct:start"/>
<to uri="http://oldhost"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: http://oldhost You can override the HTTP endpoint URI by adding a header with the key Exchange.HTTP_URI on the message.
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelHttpUri", constant("http://newhost"))
.to("http://oldhost"); <route>
<from uri="direct:start"/>
<setHeader name="CamelHttpUri">
<constant>http://newhost</constant>
</setHeader>
<to uri="http://oldhost"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelHttpUri
constant: "http://newhost"
- to:
uri: http://oldhost In the sample above, Camel will call the http://newhost despite the endpoint is configured with http://oldhost.
If the http endpoint is working in bridge mode, it will ignore the message header of Exchange.HTTP_URI.
Configuring URI Parameters
The http producer supports URI parameters to be sent to the HTTP server. The URI parameters can either be set directly on the endpoint URI or as a header with the key Exchange.HTTP_QUERY on the message.
-
Java
-
XML
-
YAML
from("direct:start")
.to("http://oldhost?order=123&detail=short"); <route>
<from uri="direct:start"/>
<to uri="http://oldhost?order=123&detail=short"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: http://oldhost
parameters:
order: 123
detail: short Or options provided in a header:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelHttpQuery", constant("order=123&detail=short"))
.to("http://oldhost"); <route>
<from uri="direct:start"/>
<setHeader name="CamelHttpQuery">
<constant>order=123&detail=short</constant>
</setHeader>
<to uri="http://oldhost"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelHttpQuery
constant: "order=123&detail=short"
- to:
uri: http://oldhost How to set the http method (GET/PATCH/POST/PUT/DELETE/HEAD/OPTIONS/TRACE) to the HTTP producer
Set the httpMethod option of the endpoint, as in Which HTTP method will be used. The CamelHttpMethod header sets the method for each message, when the endpoint has no httpMethod option. Here is an example with the header:
-
Java
-
XML
-
YAML
from("direct:start")
.setHeader("CamelHttpMethod", constant("POST"))
.to("http://www.google.com")
.to("mock:results"); <route>
<from uri="direct:start"/>
<setHeader name="CamelHttpMethod">
<constant>POST</constant>
</setHeader>
<to uri="http://www.google.com"/>
<to uri="mock:results"/>
</route> - route:
from:
uri: direct:start
steps:
- setHeader:
name: CamelHttpMethod
constant: POST
- to:
uri: http://www.google.com
- to:
uri: mock:results Timeouts and dead or silent servers
The component passes to Apache HttpClient only the timeouts that you set to another value than their default, so the defaults below are those of HttpClient 5. They describe how the client library behaves, approximately, not guarantees of Camel. All values are in milliseconds, and can be set on the component or on the endpoint (the endpoint wins).
| Option | Default | What it bounds |
|---|---|---|
| 3 minutes | Opening a new connection, including the TLS handshake. |
| 3 minutes | Each read on a connection of the endpoint’s connection pool: a server that stops sending fails the request after this time. |
| not set | When set, it replaces |
| 3 minutes | Waiting for a free connection of the pool ( |
A server that stops answering without closing the connection (the host is gone, or a firewall or NAT drops the packets) blocks the request for the read timeout: with the defaults the exchange fails after about 3 minutes with a SocketTimeoutException. HttpClient does not retry a request that timed out, whatever its method; a redelivery of the Camel error handler sends it again. Set the timeouts to what your service needs:
https://api.example.com/orders?connectTimeout=5000&soTimeout=30000&connectionRequestTimeout=5000 soTimeout, connectionTimeToLive, connectionIdleTimeout and validateAfterInactivity are settings of the connection pool that the component creates for the endpoint: they do not apply when you set your own clientConnectionManager on the component. |
Pooled connections closed by the server or by a NAT
The endpoint keeps connections open for reuse. Before reusing a connection that has been idle for more than validateAfterInactivity (component option, milliseconds, 2 seconds by default), HttpClient checks that the server has not closed it. A request sent sooner on a connection that the server closed fails with NoHttpResponseException. HttpClient retries it once only when the method is idempotent (GET, HEAD, PUT, DELETE, OPTIONS, TRACE), so a POST or a PATCH fails and needs a redelivery of the Camel error handler. With validateAfterInactivity=0, HttpClient checks the connection before each reuse, which costs a read of up to 1 millisecond per request; a negative value turns the check off.
A NAT, firewall or load balancer that drops an idle connection silently does not close it, so neither the pool nor the check above can see it: the next request on it waits for the read timeout and fails, without a retry by HttpClient. To keep the pool from reusing such a connection:
-
connectionIdleTimeout(component option, milliseconds): the maximum time a connection can stay idle in the pool and still be reused; a connection idle for longer is closed when it would be reused, and the request opens a new one. It applies whateverKeep-Alivetimeout the server announces. Not set by default. Set it below the idle timeout of the NAT, firewall or load balancer. -
httpClient.connectionKeepAlive(milliseconds): how long an idle connection is kept for reuse when the response of the server has noKeep-Aliveheader with a timeout; 3 minutes by default. Set it below the idle timeout of the NAT or firewall: it does not help when the server announces a longer timeout. -
connectionTimeToLive(component option, milliseconds): the maximum age of a connection, counted from its creation, whether it was busy or idle. Below the idle timeout of the NAT or firewall it works too, at the cost of reconnecting busy connections as well.
For example, in application.properties, for a NAT that drops connections idle for 5 minutes:
camel.component.https.connection-idle-timeout=240000 Configuring a Proxy
The HTTP component provides a way to configure a proxy.
-
Java
-
XML
-
YAML
from("direct:start")
.to("http://oldhost?proxyAuthHost=www.myproxy.com&proxyAuthPort=80"); <route>
<from uri="direct:start"/>
<to uri="http://oldhost?proxyAuthHost=www.myproxy.com&proxyAuthPort=80"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: http://oldhost
parameters:
proxyAuthHost: www.myproxy.com
proxyAuthPort: 80 There is also support for proxy authentication via the proxyAuthUsername and proxyAuthPassword options.
Using proxy settings outside of URI
Deprecated
To avoid System properties conflicts, you can set proxy configuration only from the CamelContext or URI.
Java DSL :
CamelContext global options configuration (deprecated)context.getGlobalOptions().put("http.proxyHost", "172.168.18.9");
context.getGlobalOptions().put("http.proxyPort", "8080"); Spring XML
<camelContext>
<globalOptions>
<globalOption key="http.proxyHost" value="172.168.18.9"/>
<globalOption key="http.proxyPort" value="8080"/>
</globalOptions>
</camelContext> Camel uses these global options only when useSystemProperties is false, the default. The JVM system properties, such as http.proxyHost, are only used with useSystemProperties=true, see Using System Properties. The proxy options of the endpoint or the component, such as proxyAuthHost and proxyAuthPort, take precedence over both.
There is also a http.proxyScheme property you can set to explicitly configure the scheme to use.
| Using GlobalOptions (as shown above) is deprecated. Instead, configure proxy settings on the HTTP component level. |
Configuring charset
If you are using POST to send data you can configure the charset using the Exchange property:
exchange.setProperty(Exchange.CHARSET_NAME, "ISO-8859-1"); Example with scheduled poll
This sample polls the Google homepage every 10 seconds and write the page to the file message.html:
-
Java
-
XML
-
YAML
from("timer://foo?fixedRate=true&delay=0&period=10000")
.to("http://www.google.com")
.setHeader("CamelFileName", constant("message.html"))
.to("file:target/google"); <route>
<from uri="timer://foo?fixedRate=true&delay=0&period=10000"/>
<to uri="http://www.google.com"/>
<setHeader name="CamelFileName">
<constant>message.html</constant>
</setHeader>
<to uri="file:target/google"/>
</route> - route:
from:
uri: timer://foo
parameters:
fixedRate: true
delay: 0
period: 10000
steps:
- to:
uri: http://www.google.com
- setHeader:
name: CamelFileName
constant: message.html
- to:
uri: file:target/google URI Parameters from the endpoint URI
In this sample, we have the complete URI endpoint that is just what you would have typed in a web browser. Multiple URI parameters can of course be set using the & character as separator, just as you would in the web browser. Camel does no tricks here.
ProducerTemplate test API// we query for Camel at the Google page
template.sendBody("http://www.google.com/search?q=Camel", null); URI Parameters from the Message
ProducerTemplate test API with headersMap headers = new HashMap();
headers.put(Exchange.HTTP_QUERY, "q=Camel&lr=lang_en");
// we query for Camel and English language at Google
template.sendBody("http://www.google.com/search", null, headers); In the header value above notice that it should not be prefixed with ? and you can separate parameters as usual with the & char.
Getting the Response Code
You can get the HTTP response code from the HTTP component by getting the value from the Out message header with Exchange.HTTP_RESPONSE_CODE.
ProducerTemplate and Processor to inspect response codeExchange exchange = template.send("http://www.google.com/search", e -> {
e.getIn().setHeader("CamelHttpQuery", "hl=en&q=activemq");
});
Message out = exchange.getMessage();
int responseCode = out.getHeader("CamelHttpResponseCode", Integer.class); Defining specific properties of Apache HTTP client via Camel parameters
There are different parameters you could set in a route, that will influence the behavior of the Apache HTTP Client.
Most of the option are available here: Apache HttpClient Request Config Builder.
-
httpClient.authenticationEnabled - Determines whether authentication should be handled automatically.
-
httpClient.circularRedirectsAllowed - Determines whether circular redirects (redirects to the same location) should be allowed.
-
httpClient.connectionKeepAlive - Determines the default of value of connection keep-alive time period when not explicitly communicated by the origin server with a Keep-Alive response header.
-
httpClient.connectionRequestTimeout - Determines the connection lease request timeout used when requesting a connection from the connection manager.
-
httpClient.contentCompressionEnabled - Determines whether the target server is requested to compress content.
-
httpClient.cookieSpec - Determines the name of the cookie specification to be used for HTTP state management.
-
httpClient.defaultKeepAlive - Determines the default keep-alive
-
httpClient.expectContinueEnabled - Determines whether the 'Expect: 100-Continue' handshake is enabled for entity enclosing methods.
-
httpClient.hardCancellationEnabled - Determines whether request cancellation should kill the underlying connection.
-
httpClient.maxRedirects - Determines the maximum number of redirects to be followed.
-
httpClient.protocolUpgradeEnabled - Determines whether the client server should automatically attempt to upgrade to a safer or a newer version of the protocol, whenever possible.
-
httpClient.redirectsEnabled - Determines whether redirects should be handled automatically.
-
httpClient.responseTimeout - Determines the timeout until arrival of a response from the opposite endpoint.
Disabling Cookies
To disable cookies in the CookieStore, you can set the HTTP Client to ignore cookies by adding this URI option: httpClient.cookieSpec=ignore. This doesn’t affect cookies manually set in the Cookie header
Authentication
The HTTP producer authenticates with the options of the endpoint. To use the same settings for all the endpoints of a component, set them in an HttpConfiguration given to the httpConfiguration option of the component.
| Method | Options |
|---|---|
Basic |
|
Bearer |
|
NTLM (deprecated) |
|
By default, the credentials are sent only when the server answers with 401 Unauthorized and a WWW-Authenticate header that asks for them. With authenticationPreemptive=true, the Basic credentials or the Bearer token are sent with the first request. Use it when the server does not send a challenge, or when the message body is a stream that can be sent only once: otherwise the request fails with NonRepeatableRequestException when the server asks for the credentials.
When followRedirects=true, a redirect to another host does not receive the credentials.
The following example sends a bearer token, read from a property, with each request:
-
Java
-
XML
-
YAML
from("direct:start")
.to("https://api.example.com/orders?authMethod=Bearer&authBearerToken={{orders.token}}&authenticationPreemptive=true"); <route>
<from uri="direct:start"/>
<to uri="https://api.example.com/orders?authMethod=Bearer&authBearerToken={{orders.token}}&authenticationPreemptive=true"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: "https://api.example.com/orders"
parameters:
authMethod: Bearer
authBearerToken: "{{orders.token}}"
authenticationPreemptive: true To get the token from an authorization server, use the OAuth2 options described in the next section.
OAuth2 Support
To get an access token from an Authorization Server and fill that in Authorization header to do requests to protected services, you will need to use oauth2ClientId, oauth2ClientSecret and oauth2TokenEndpoint properties, and those should be defined as specified at RFC 6749 and provided by your Authorization Server.
In below example camel will do an underlying request to https://localhost:8080/realms/master/protocol/openid-connect/token using provided credentials (client id and client secret), then will get access_token from response and lastly will fill it at Authorization header of request which will be done to https://localhost:9090.
-
Java
-
XML
-
YAML
from("direct:start")
.to("https://localhost:9090/?oauth2ClientId=my-client-id&oauth2ClientSecret=my-client-secret&oauth2TokenEndpoint=https://localhost:8080/realms/master/protocol/openid-connect/token&oauth2Scope=my-scope"); <route>
<from uri="direct:start"/>
<to uri="https://localhost:9090/?oauth2ClientId=my-client-id&oauth2ClientSecret=my-client-secret&oauth2TokenEndpoint=https://localhost:8080/realms/master/protocol/openid-connect/token&oauth2Scope=my-scope"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: "https://localhost:9090/"
parameters:
oauth2ClientId: my-client-id
oauth2ClientSecret: my-client-secret
oauth2TokenEndpoint: "https://localhost:8080/realms/master/protocol/openid-connect/token"
oauth2Scope: my-scope Additional support for OAuth2 is for RFC 8707 where a Resource Indicator must be provided in the body:
-
Java
-
XML
-
YAML
from("direct:start")
.to("https://localhost:9090/?oauth2ClientId=my-client-id&oauth2ClientSecret=my-client-secret&oauth2TokenEndpoint=https://localhost:8080/realms/master/protocol/openid-connect/token&oauth2Scope=my-scope&oauth2ResourceIndicator=https://localhost:9090"); <route>
<from uri="direct:start"/>
<to uri="https://localhost:9090/?oauth2ClientId=my-client-id&oauth2ClientSecret=my-client-secret&oauth2TokenEndpoint=https://localhost:8080/realms/master/protocol/openid-connect/token&oauth2Scope=my-scope&oauth2ResourceIndicator=https://localhost:9090"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: "https://localhost:9090/"
parameters:
oauth2ClientId: my-client-id
oauth2ClientSecret: my-client-secret
oauth2TokenEndpoint: "https://localhost:8080/realms/master/protocol/openid-connect/token"
oauth2Scope: my-scope
oauth2ResourceIndicator: "https://localhost:9090" | Resource Indicator is the URL to the actual endpoint as defined in the component URI. |
| Camel only provides support for OAuth2 client credentials flow |
| Camel does not perform any validation in access token. It’s up to the underlying service to validate it. |
Caching tokens
With oauth2CacheTokens=true, Camel caches the token until it expires (see oauth2CachedTokensDefaultExpirySeconds and oauth2CachedTokensExpirationMarginSeconds). The option oauth2CachedTokensKey decides which requests share a cached token:
-
HOST_ONLY(default): one token shared by all requests to the same scheme, host and port. -
HOST_AND_PATH: one token per path. The query is not taken into account. -
FULL_URI: one token per request URI, including the query (the behaviour before Camel 4.23).
The client id, client secret, token endpoint, scope and resource indicator are always part of the key. The token request itself does not depend on the request URI, so the default HOST_ONLY does not request a new token for every new URI, for example with dynamic paths or queries in toD.
-
Java
-
XML
-
YAML
from("direct:start")
.toD("https://localhost:9090/event/${header.eventId}?oauth2ClientId=my-client-id&oauth2ClientSecret=my-client-secret&oauth2TokenEndpoint=https://localhost:8080/realms/master/protocol/openid-connect/token&oauth2CacheTokens=true&oauth2CachedTokensKey=HOST_ONLY"); <route>
<from uri="direct:start"/>
<toD uri="https://localhost:9090/event/${header.eventId}?oauth2ClientId=my-client-id&oauth2ClientSecret=my-client-secret&oauth2TokenEndpoint=https://localhost:8080/realms/master/protocol/openid-connect/token&oauth2CacheTokens=true&oauth2CachedTokensKey=HOST_ONLY"/>
</route> - route:
from:
uri: direct:start
steps:
- toD:
uri: "https://localhost:9090/event/${header.eventId}"
parameters:
oauth2ClientId: my-client-id
oauth2ClientSecret: my-client-secret
oauth2TokenEndpoint: "https://localhost:8080/realms/master/protocol/openid-connect/token"
oauth2CacheTokens: true
oauth2CachedTokensKey: HOST_ONLY For other rules, implement org.apache.camel.component.http.OAuth2CachedTokensKeyResolver and refer to it with oauth2CachedTokensKeyResolver=#myResolver. It takes precedence over oauth2CachedTokensKey. When it returns null, the token for that request is not cached.
Vault-backed credential rotation
When using vault-backed property placeholders (e.g. {{aws:mySecret/password}}) with DefaultContextReloadStrategy, rotated credentials are picked up automatically because Camel rebuilds all routes and their endpoints from the updated component configuration after each reload event. No special configuration is needed for camel-http: the fresh endpoints created during the route restart carry the newly resolved credentials.
camel-oauth Profile Support
The oauthProfile endpoint option integrates with camel-oauth to resolve a bearer token per HTTP request without managing the token endpoint credentials on every endpoint URI.
Set oauthProfile to the name of a profile configured under camel.oauth.<profileName>.* in your application properties. On each outgoing request Camel resolves a fresh bearer token (or reuses the cached one until it expires) from that profile and injects it as an Authorization: Bearer header.
-
Java
-
XML
-
YAML
from("direct:start")
.to("https://api.example.com/data?oauthProfile=myProfile"); <route>
<from uri="direct:start"/>
<to uri="https://api.example.com/data?oauthProfile=myProfile"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: "https://api.example.com/data"
parameters:
oauthProfile: myProfile The profile properties follow the camel-oauth convention:
camel.oauth.myProfile.client-id=my-client-id
camel.oauth.myProfile.client-secret=my-client-secret
camel.oauth.myProfile.token-endpoint=https://idp.example.com/token | The bearer token is only attached to requests directed at the endpoint’s own authority (scheme, host, and port). Redirects to a different host or port do not receive it, preventing accidental token leakage. |
oauthProfile requires camel-oauth on the classpath. It can be used alongside the oauth2* options: oauth2* options manage the full OAuth2 credential flow on the endpoint URI, while oauthProfile delegates token acquisition to a named camel-oauth profile. If both are set, the oauth2* token is used and a WARN is logged at startup. |
Logging HTTP activity
With logHttpActivity=true (on the component or the endpoint), the HTTP requests that are sent and the HTTP responses that are received are logged, with their headers and body. To control what is logged, configure a LoggingHttpActivityListener bean with the options you need and set it as httpActivityListener.
The value of a header that carries a credential is always masked, also when logMask is not enabled. Which headers those are is decided by SensitiveUtils.isSensitiveHeader in camel-util: a header whose name matches a sensitive key (such as Authorization), whose name ends in token, key, secret, password, auth, authorization, credential or credentials (such as X-Amz-Security-Token or Ocp-Apim-Subscription-Key), or that is a well-known credential header such as Proxy-Authorization, Cookie or Set-Cookie, and any header that the HTTP client flags as sensitive. A header such as Idempotency-Key, whose name ends in key but that carries no secret, is not masked. The header name is kept, so the log shows Authorization: xxxxx.
With logMask=true, the values of the other headers and the body are also masked with the masking formatter of Camel, which masks values of sensitive keys such as password=secret.
Advanced Usage
If you need more control over the HTTP producer, you should use the HttpComponent where you can set various classes to give you custom behavior.
Setting up SSL for HTTP Client
Using the JSSE Configuration Utility
The HTTP component supports SSL/TLS configuration through the Camel JSSE Configuration Utility. This utility greatly decreases the amount of component-specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the HTTP component.
Programmatic configuration of the component
SSLContextParameters setupKeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("file:/users/home/server/keystore.jks");
ksp.setPassword("keystorePassword");
KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
kmp.setKeyPassword("keyPassword");
SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);
HttpComponent httpComponent = getContext().getComponent("https", HttpComponent.class);
httpComponent.setSslContextParameters(scp); Spring DSL based configuration of endpoint
<camel:sslContextParameters
id="sslContextParameters">
<camel:keyManagers
keyPassword="keyPassword">
<camel:keyStore
resource="file:/users/home/server/keystore.jks"
password="keystorePassword"/>
</camel:keyManagers>
</camel:sslContextParameters>
<to uri="https://127.0.0.1/mail/?sslContextParameters=#sslContextParameters"/> Configuring Apache HTTP Client Directly
Basically, a camel-http component is built on the top of Apache HttpClient. Please refer to SSL/TLS customization (even if the link is referring to an article about version 4, it is still more or less relevant moreover there is no equivalent for version 5) for details or have a look into the org.apache.camel.component.http.HttpsServerTestSupport unit test base class.
You can also implement a custom org.apache.camel.component.http.HttpClientConfigurer to do some configuration on the http client if you need full control of it.
However, if you just want to specify the keystore and truststore, use sslContextParameters as shown above. If you implement an HttpClientConfigurer, you can hook it up from your camel route builder class like so:
HttpClientConfigurer setupHttpComponent httpComponent = getContext().getComponent("http", HttpComponent.class);
httpComponent.setHttpClientConfigurer(new MyHttpClientConfigurer()); If you are doing this using the Spring DSL, you can specify your HttpClientConfigurer using the URI. For example:
<bean id="myHttpClientConfigurer"
class="my.https.HttpClientConfigurer">
</bean>
<to uri="https://myhostname.com:443/myURL?httpClientConfigurer=#myHttpClientConfigurer"/> Using HTTPS to authenticate gotchas
An end user reported that he had a problem with authenticating with HTTPS. The problem was eventually resolved by providing a custom configured org.apache.hc.core5.http.protocol.HttpContext:
-
1. Create a (Spring) factory for HttpContexts:
HttpContext factory for preemptive basic authenticationpublic class HttpContextFactory {
private String httpHost = "localhost";
private String httpPort = 9001;
private String user = "some-user";
private String password = "my-secret";
private HttpClientContext context = HttpClientContext.create();
private BasicAuthCache authCache = new BasicAuthCache();
private BasicScheme basicAuth = new BasicScheme();
public HttpContext getObject() {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password.toCharArray());
BasicCredentialsProvider provider = new BasicCredentialsProvider();
HttpHost host = new HttpHost(httpHost, httpPort);
provider.setCredentials(host, credentials);
authCache.put(host, basicAuth);
httpContext.setAuthCache(authCache);
httpContext.setCredentialsProvider(provider);
return httpContext;
}
// getter and setter
} -
2. Declare an` HttpContext` in the Spring application context file:
HttpContext factory<bean id="myHttpContext" factory-bean="httpContextFactory" factory-method="getObject"/> -
3. Reference the context in the http URL:
HttpContext bean<to uri="https://myhostname.com:443/myURL?httpContext=#myHttpContext"/> Using different SSLContextParameters
The sslContextParameters option of an endpoint takes precedence over the one of the component. So endpoints of the same component can use different SSLContextParameters instances, and you do not need a component per instance. A dynamic endpoint can refer to one as well:
-
Java
-
YAML
from("direct:start")
.toD("https://${header.host}/orders?sslContextParameters=#mySSL"); - route:
from:
uri: direct:start
steps:
- toD:
uri: "https://${header.host}/orders?sslContextParameters=#mySSL" To define mySSL in XML or YAML, see JSSE Utility.
With Camel Main, the camel.ssl.* properties set up global SSLContextParameters instead. An https endpoint uses them when the https component has useGlobalSslContextParameters=true, and neither the endpoint nor the component sets sslContextParameters:
camel.ssl.enabled=true
camel.ssl.trust-store=truststore.p12
camel.ssl.trust-store-password=changeit
camel.component.https.use-global-ssl-context-parameters=true When the component or the endpoint has a clientConnectionManager, Camel uses that connection manager as it is, and sslContextParameters is not applied.
Removing http protocol headers in the Camel Message
In camel there are a number of components that use the http protocol headers to do their business.
The components include camel-http, camel-jetty, camel-cxf, etc.
If you are using these component, you may pay attention to the HTTP protocol headers:
Exchange.CONTENT_ENCODING
Exchange.CONTENT_TYPE
Exchange.HTTP_BASE_URI
Exchange.HTTP_CHARACTER_ENCODING
Exchange.HTTP_METHOD
Exchange.HTTP_PATH
Exchange.HTTP_QUERY
Exchange.HTTP_RESPONSE_CODE If you don’t want these headers to bother your other endpoints, you can remove these headers using Remove Headers EIP as follows:
-
Java
-
XML
-
YAML
from("jetty://http://myhost:9000/myservice/")
.removeHeaders("CamelHttp*")
.to("otherEndpoint"); <route>
<from uri="jetty://http://myhost:9000/myservice/"/>
<removeHeaders pattern="CamelHttp*" />
<to uri="otherEndpoint"/>
</route> - route:
from:
uri: jetty://http://myhost:9000/myservice/
steps:
- removeHeaders:
pattern: "CamelHttp*"
- to:
uri: otherEndpoint