I want to create a custom Client API (on a non-Java RS environment). The API needs to have a custom base URL and a custom Header.
I achieve the custom base URL with the following and it works like a charm
RestClientBuilder.newBuilder()
.baseUri({{myAPUURI}})
.build(myAPI.class);
However, I could not find any solution to allow custom headers tightly coupled with the generated API. The only working solution I can do is to have a static variable in implementing the ClientHeadersFactory.
public class ApiHeader implements ClientHeadersFactory {
public static String userToken;
@Override
public MultivaluedMap<String, String> update(
MultivaluedMap<String, String> incomingHeaders,
MultivaluedMap<String, String> clientOutgoingHeaders
) {
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.add("authorization", userToken);
return map;
}
}
However, I have multiple instances of the rest client operating simultaneously, hence this solution would not be thread-safe. How could I reliably inject the token into the Rest client?
You can do something like:
RestClientBuilder.newBuilder()
.baseUri({{myAPUURI}})
.register(new CustomHeaderProvider("foo", "bar"))
.build(myAPI.class);
where CustomHeaderProvider
looks like this:
public class CustomHeaderProvider implements ClientRequestFilter {
private final String name;
private final String value;
public CustomHeaderProvider(String name, String value) {
this.name = name;
this.value = value;
}
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
requestContext.getHeaders().add(name, value);
}
}