How to POST form-url-encoded data with Spring Cloud Feign

时间:2016-03-04 18:08:01

标签: spring-mvc spring-cloud spring-cloud-feign feign

Using spring-mvc annotations, how can I define an @FeignClient that can POST form-url-encoded?

4 个答案:

答案 0 :(得分:9)

使用表格编码器进行假装:https://github.com/OpenFeign/feign-form,您的假装配置可能如下所示:

class CoreFeignConfiguration {

  @Autowired
  private ObjectFactory<HttpMessageConverters> messageConverters

  @Bean
  @Primary
  @Scope(SCOPE_PROTOTYPE)
  Encoder feignFormEncoder() {
      new FormEncoder(new SpringEncoder(this.messageConverters))
  }
}

然后,客户端可以像这样映射:

@FeignClient(name = 'client', url = 'localhost:9080', path ='/rest', configuration = CoreFeignConfiguration)
interface CoreClient {

    @RequestMapping(value = '/business', method = POST, consumes = MediaType.APPLICATION_FORM_URLENCODED)
    @Headers('Content-Type: application/x-www-form-urlencoded')
    void activate(Map<String, ?> formParams)
}

答案 1 :(得分:3)

带有kazuar解决方案简化版本的完整Java代码可与Spring Boot一起使用:

import java.util.Map;

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE;

@FeignClient(name = "srv", url = "http://s.com", configuration = Client.Configuration.class)
public interface Client {

    @PostMapping(value = "/form", consumes = APPLICATION_FORM_URLENCODED_VALUE)
    void login(@RequestBody Map<String, ?> form);

    class Configuration {

        @Bean
        Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> converters) {
            return new SpringFormEncoder(new SpringEncoder(converters));
        }
    }
}

依赖性:

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

答案 2 :(得分:0)

您必须在Feign编码器中使用FormEncoder来处理POST中以url形式编码的数据。

包括对您应用程序的依赖性:

行家:

<dependency>
  <groupId>io.github.openfeign.form</groupId>
  <artifactId>feign-form</artifactId>
  <version>3.8.0</version>
</dependency>

像这样将FormEncoder添加到Feign.Builder中:

SomeFeign sample  = Feign.builder()
                      .encoder(new FormEncoder(new JacksonEncoder()))
                      .target(SomeFeign.class, "http://sample.test.org");

在Feign界面中

@RequestLine("POST /submit/form")
@Headers("Content-Type: application/x-www-form-urlencoded")
void from (@Param("field1") String field1, @Param("field2") String field2);

更多信息参考: https://github.com/OpenFeign/feign-form

答案 3 :(得分:-1)

请查看此issue。看起来它包含了解决问题的方法。