How to send POST request by Spring cloud Feign

后端 未结 3 456
执念已碎
执念已碎 2020-12-29 12:14

It\'s my Feign interface

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


        
相关标签:
3条回答
  • 2020-12-29 12:55

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-29 12:59

    Specify the correct encoder for handle form encoded request

    you can specify multi encoder example json/xml/formhttpurl encoded

    @Bean
    public Encoder feignEncoder() {
        ObjectFactory<HttpMessageConverters> objectFactory = () ->
                new HttpMessageConverters(new FormHttpMessageConverter());
        return new SpringEncoder(objectFactory);
    }
    

    Important FormHttpMessageConverter serialize only MultiValueMap subsclass

    0 讨论(0)
  • 2020-12-29 13:08

    It seems to me that Map is not valid for form body. MultiValueMap works just fine.

    Feign client:

    @FeignClient(name = "name", url="url", configuration = FromUrlEncodedClientConfiguration.class)
    public interface PayPalFeignClient {
    
        @RequestMapping(value = "/", method = POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
        @Headers("Content-Type: application/x-www-form-urlencoded")
        String foo(MultiValueMap<String, ?> formParams);
    }
    

    Config:

    @Configuration
    public class FromUrlEncodedClientConfiguration {
    
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
    
        @Bean
        @Primary
        @Scope(SCOPE_PROTOTYPE)
        Encoder feignFormEncoder() {
            return new FormEncoder(new SpringEncoder(this.messageConverters));
        }
    }
    

    Gradle dependencies:

    compile group: 'io.github.openfeign.form', name: 'feign-form', version: '2.0.2'
    compile group: 'io.github.openfeign.form', name: 'feign-form-spring', version: '2.0.5'
    

    After that all you have to do is call it with a MultivalueMap parameter.

    0 讨论(0)
提交回复
热议问题