mac
mac

Reputation: 2724

How to set HTTP header in RESTEasy 3.0 client framework (with ResteasyClientBuilder and ResteasyWebTarget)?

I'm trying to figure out how to set HTTP headers similar to what was explained here:

However, I want to use RESTeasy 3.0 functionality (ResteasyClientBuilder and ResteasyWebtarget) and not the deprecated ProxyFactory, as explained here:

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.

Upvotes: 5

Views: 8142

Answers (1)

mac
mac

Reputation: 2724

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);
    }
}

Upvotes: 5

Related Questions