I've looked at different answers on here and they're all about adding header(s) during a request call. I would like to add headers in the client config then register it with the client itself.
I've looked around and found that I can create a custom ClientRequestFilter, but looking at the add()
method signatures, I don't see any in which I can add multiple headers - they all take like a string as the first argument, then like a list.
For example, I would like to add these headers:
Accept: 'something'
Client-ID: 'another something'
Authorization: 'OAuth more something'
I came up with the code below, but it seems only the first register()
method call is actually used. I checked the debugger and all I see is the first Accept header and the User-Agent header added by Jersey.
public OAuth2Authenticator(String header, String value) {
this.header = header;
this.value = value;
}
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
requestContext.getHeaders().add(header, value);
}
...
client = ClientBuilder.newClient(new ClientConfig());
client.register(new OAuth2Authenticator(HttpHeaders.ACCEPT, API_VERSION))
.register(new OAuth2Authenticator("Client-ID", clientId))
.register(new OAuth2Authenticator(HttpHeaders.AUTHORIZATION, "OAuth " + accessToken));
I was able to get it to work by assigning to a MultivalueMap first, then calling add()
.
MultivaluedMap<String, Object> headers = requestContext.getHeaders();
headers.add(HttpHeaders.ACCEPT, "something");
headers.add("Client-ID", another something);
headers.add(HttpHeaders.AUTHORIZATION, "OAuth more something");
...
client = ClientBuilder.newClient(new ClientConfig());
client.register(new OAuth2Authenticator( API_VERSION, clientId, accessToken));