I'm trying to figure out how to set HTTP headers similar to what was explained here:
- How to set HTTP header in RESTEasy client framework?, or here
- RESTEasy client framework authentication credentials
However, I want to use RESTeasy 3.0 functionality (ResteasyClientBuilder and ResteasyWebtarget) and not the deprecated ProxyFactory, as explained here:
- What is the substitute for Resteasy ProxyFactory class
And just to clarify, I also do not want to set the header(s) on every request / don't want them to be passed to the client, I'd like them to be set on ResteasyClientBuilder/ResteasyWebtarget level if possible.
Found a solution.
The trick is to register a ClientRequestFilter with the ResteasyClient (line #2 of the method below):
public Resource getResource(Credentials credentials) {
ResteasyClient client = new ResteasyClientBuilder().build();
client.register(new AuthHeadersRequestFilter(credentials));
return client.target(restServiceRoot).proxy(Resource.class);
}
And then have your request filter do something like:
public class AuthHeadersRequestFilter implements ClientRequestFilter {
private final String authToken;
public AuthHeadersRequestFilter(Credentials credentials) {
authToken = credentials.getAuthorizationHeader();
}
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
requestContext.getHeaders().add("Authorization", authToken);
}
}