简体   繁体   中英

Dynamic API client with dynamic custom header (Microprofile, Quarkus)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM