Disable feign encoding of PathVariables

Viewed 3470

I have the following Feign Client:

public interface MyServiceClient {
    @RequestMapping(method = RequestMethod.GET, value = "/item/{itemKey}")
    Item getItem (@PathVariable("itemKey") String itemKey);
}

The items can contains special characters like : or :: which are being encoded.

Request URL becomes something like:

  • https://myservice.com/item/a%3Ab%3A%3Ac

Rather than:

  • https://myservice.com/item/a:b::c

Can anyone help me understand how can we fix this issue?

2 Answers

OpenFeign has an issue tracking:

Guess it will be implemented by spring-cloud-feign once its done. Meanwhile, my workaround for this issue is to create a RequestInterceptor and replace %3A with :

public class MyRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        template.uri(template.path().replaceAll("%3A", ":"));
    }
}

And use this requestInterceptor to build your feignClient in the feignConfig:

@Bean
public Feign.Builder tcsClientBuilder() {
    return Feign.builder().requestInterceptor(new MyRequestInterceptor());
}

This works for me in my case:

//ICustomFeignClient =  your Feign client interface
Feign.builder()
    .client(new OkHttpClient())
    .encoder(new GsonEncoder())
    .decoder(new GsonDecoder())
    .logger(new Slf4jLogger(builderClass))
    .logLevel(Logger.Level.FULL)
    .requestInterceptor(new CustomFeignRequestInterceptor())
    .target(ICustomFeignClient, baseUrl);
                
// custom interceptor class below 
class CustomFeignRequestInterceptor implements RequestInterceptor {
               
    @Override
    public void apply(RequestTemplate requestTemplate) {
    // you can replace the string you don't want from here
    requestTemplate.uri(
        requestTemplate.request()
            .url()
            .replaceAll("%3D", "=")
            .replaceAll("%26", "&")
        );
    }
}
Related