bhosleviraj
bhosleviraj

Reputation: 99

Okhttp 3: How to add header based on path parameter

In Okhttp, how to add a header that is based on serviceId? One way would be to use url segments. But that is based on index. What if the serviceId is always not at same index in the path? Is there a way to get path parameter by name? It's a wishful thinking as I couldn't find such a way anywhere.

Retrofit:

@POST("services/{serviceId}/resources/{resourceId}")
Call<Resource> addResourceVector(@Path("serviceId") Long serviceId,
                                 @Path("resourceId") String resourceId)

Okhttp Interceptor:

public class AuthHeaderInterceptor implements Interceptor {

    private final TokenService tokenService;

    public AuthHeaderInterceptor(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();

        Request requestWithAuthToken = originalRequest.newBuilder()
            .header(HttpHeaders.AUTHORIZATION, tokenService.getToken(originalRequest.getPathParam("serviceId")) //wishful thinking
            .build();
        return chain.proceed(requestWithAuthToken);
    }
}

Bonus: getToken returns CompletableFuture. Don't think about getting token at the startup and using the same throughout. There was a proposal for async interceptor but it wasn't picked up. https://github.com/square/okhttp/issues/3714

Upvotes: 1

Views: 219

Answers (1)

Jesse Wilson
Jesse Wilson

Reputation: 40623

You can recover the function call arguments using the Invocation tag.

https://square.github.io/retrofit/2.x/retrofit/retrofit2/Invocation.html

 class InvocationLogger implements Interceptor {
   @Override public Response intercept(Chain chain) throws IOException {
     Request request = chain.request();
     Invocation invocation = request.tag(Invocation.class);
     if (invocation != null) {
       System.out.printf("%s.%s %s%n",
           invocation.method().getDeclaringClass().getSimpleName(),
           invocation.method().getName(), invocation.arguments());
     }
     return chain.proceed(request);
   }
 }

Upvotes: 2

Related Questions