Feign rest client, disable decode on specific interface methods

2.4k views Asked by At

Going through the learning curve, and came across this scenario:

Given that 90% of the calls are JSON, added a GSON decoder when building the client. However, there are some method calls in the interface that should support raw return without decoding.

@RequestLine("GET /rest/myrawmethod")
String getRawMethod();

Currently since GSON is added as a decoder, instead of returning the raw string it attempts to decode it (it does look like JSON content, but I want to bypass decoding). I can't seem to find an easy way to disable for specific interface methods when not to use the GSON decoder as the exception.

Thanks!

2

There are 2 answers

1
dhartford On BEST ANSWER

Saw some references to various approaches, this seems like the best avenue at this time:

@RequestLine("GET /rest/myrawmethod")
feign.Response getRawMethod();

Then when you go to parse the response, use something like:

feign.codec.Decoder dc = new Decoder.Default();
String strresponse = dc.decode(myfeignresponse, String.class); //wrapped with exception handling

Good way to prototype in scenarios where you don't have anything around the REST payload, only the method calls...or want to do something more exotic (like use the feign.Response streaming methods).

1
Ian Phillips On

Try making a custom Decoder like this:

    class StringHandlingDecoder implements Decoder {
        private final Decoder defaultDecoder;

        StringHandlingDecoder(Decoder defaultDecoder) {
            this.defaultDecoder = defaultDecoder;
        }

        @Override
        public Object decode(Response response, Type type) throws IOException, FeignException {
            if (type == String.class) {
                return new StringDecoder().decode(response, type);
            } else {
                return this.defaultDecoder.decode(response, type);
            }
        }
    }

Then build your client like this:

Feign.builder()
   .decoder(new StringHandlingDecoder(new GsonDecoder()))
   .build();