5

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.

Community
  • 1
  • 1
mac
  • 2,672
  • 4
  • 31
  • 43

1 Answers1

5

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);
    }
}
mac
  • 2,672
  • 4
  • 31
  • 43
  • @mac: Is this Thread-safe. Say, for example, if I have 4 headers in first request and 3 headers in the second request will this second request will have 3 or 4 headers? – Arun Feb 04 '16 at 08:35
  • Not sure I understand the question right, but ... I'm pretty sure that this is thread-safe. As you see the filter gets the ClientRequestContext, so I don't see a way how two requests could step on each other. That's of course assuming that all requests use the same credentials, and that no other filter sets the same header. Here's another, older, article that I found: http://stackoverflow.com/questions/6929378/how-to-set-http-header-in-resteasy-client-framework Hope this helps! – mac Feb 05 '16 at 16:47