How to send POST request by Spring cloud Feign

koa73 picture koa73 · Feb 23, 2017 · Viewed 28k times · Source

It's my Feign interface

@FeignClient(
        name="mpi",
        url="${mpi.url}",
        configuration = FeignSimpleEncoderConfig.class
)
public interface MpiClient {

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> getPAReq(@QueryMap Map<String, String> queryMap
    );
}

and my custom configuration

public class FeignSimpleEncoderConfig {
    public static final int FIVE_SECONDS = 5000;

    @Bean
    public Logger.Level feignLogger() {
        return Logger.Level.FULL;
    }

    @Bean
    public Request.Options options() {
        return new Request.Options(FIVE_SECONDS, FIVE_SECONDS);
    }

    @Bean 
    @Scope("prototype")
    public Feign.Builder feignBuilder() {
        return Feign.builder()
                .encoder(new FormEncoder());
    }
}

If I send request like this I see that my request send Content-Type: application/json;charset=UTF-8. But if I set content type

consumes = "application/x-www-form-urlencoded"

I've this error message

feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type [java.util.HashMap] and content type [application/x-www-form-urlencoded]
    at org.springframework.cloud.netflix.feign.support.SpringEncoder.encode(SpringEncoder.java:108) ~[spring-cloud-netflix-core-1.1.7.RELEASE.jar:1.1.7.RELEASE]

How to send POST request, I think I should make something more with Encoder. Thanks for your help.

Answer

koa73 picture koa73 · Feb 24, 2017

First of all you should change your Feign interface like this:

@FeignClient (
    configuration = FeignSimpleEncoderConfig.class
)
public interface MpiClient {
   @RequestMapping(method = RequestMethod.POST)
   ResponseEntity<String> getPAReq(Map<String, ?> queryMap);
}

Then you should set the encoder during feign configuration:

public class FeignSimpleEncoderConfig {
    @Bean
    public Encoder encoder() {
        return new FormEncoder();
    }
}