In my Camel SpringBoot app I send a request (which includes a number of specific HTTP headers) and receive the 302 from the remote service. Camel automatically follows the redirect but includes all headers previously set, which causes some problems on the other side. Is there any way to control this behavior?
CodePudding user response:
The most obvious is to remove specific headers in the Camel route with
.removeHeaders("Camel*")
This of course must be done for every header pattern and also multiple times if you have multiple outbound connections.
But Camel also has the concept of a HeaderFilterStrategy
. Most components have a default implementation that is used by default.
In the case of HTTP this is HttpHeaderFilterStrategy
. It is applied for all HTTP connections and filters the following headers:
- content-length
- content-type
- host
- cache-control
- connection
- date
- pragma
- trailer
- transfer-encoding
- upgrade
- via
- warning
- Camel*
- org.apache.camel*
You are free to implement your own custom HeaderFilterStrategy
or extend one of Camel. You can then register it as a Spring bean and configure your endpoints to use it where needed.
.to("http:myEndpoint?&headerFilterStrategy=#myHeaderFilter") // myHeaderFilter = name of the Spring bean
CodePudding user response:
I was able to solve this by creating a custom HTTP configurer which adds an interceptor to the request, e.g.
public class RedirectHttpClientConfigurer implements HttpClientConfigurer {
@Override
public void configureHttpClient(HttpClientBuilder clientBuilder) {
clientBuilder.addInterceptorFirst(new RedirectInterceptor());
}
public class RedirectInterceptor implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
Object httpResponseContextAttr = context.getAttribute("http.response");
if (httpResponseContextAttr != null) {
HttpResponse httpResponse = (HttpResponse) httpResponseContextAttr;
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode > 299 && statusCode < 399) {
request.removeHeaders("Authorization");
}
}
}
}
}
Then I configured it as a bean:
<spring:bean id="redirectConfigurer" class="com.foo.bar.RedirectHttpClientConfigurer"/>
and referenced it in the endpoint:
<to uri="http://com.foo.bar?httpClientConfigurer=#redirectConfigurer"/>