How to configure HTTP header in RESTEasy 3.0 client environment (with ResteasyClientBuilder and ResteasyWebTarget)?

I am trying to figure out how to set up HTTP headers similar to what was explained here:

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

And just to clarify, I also do not want to set a header for each request / I do not want them to be passed to the client, I would like them to be set at the level of ResteasyClientBuilder / ResteasyWebtarget, if possible.

+4
source share
1 answer

Found a solution.

The trick is to register a ClientRequestFilter with 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 try the query filter:

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);
    }
}
+3
source

Source: https://habr.com/ru/post/1526804/


All Articles