如何使用Spring Cloud Feign发布表单URL编码的数据



使用spring-mvc注释:

  • 如何定义可以POST form-url-encoded @FeignClient

使用 FormEncoder 进行伪装:

  • https://github.com/OpenFeign/feign-form

您的 Feign 配置可能如下所示:

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)
}
完整的

Java代码,带有简化版本的kazuar解决方案,适用于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")
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>

为了补充接受的答案,还可以使用 POJO 代替 Map<String, ?> 将表单参数传递给假装客户端:

@FeignClient(configuration = CustomConfig.class)
interface Client {
    @PostMapping(
        path = "/some/path", 
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    void postComment(CommentFormDto formDto);
    ...
}
...
@Configuration
class CustomConfig {
    @Bean
    Encoder formEncoder() {
        return new feign.form.FormEncoder();
    }
}
...
class CommentFormDto {
    private static String willNotBeSerialized;
    private final Integer alsoWillNotBeSerialized;
    @feign.form.FormProperty("author_id")
    private Long authorId;
    private String message;
    @feign.form.FormProperty("ids[]")
    private List<Long> ids;
    
    /* getters and setters omitted for brevity */  
}

这将导致请求的正文如下所示:

author_id=42&message=somemessage&ids[]=1&ids[]=2

@FormProperty注释允许设置自定义字段名称;请注意,POJO的静态或最终字段以及继承的字段不会被序列化为表单内容。

对于 Kotlin:

import org.springframework.http.MediaType
@FeignClient(configuration = [CustomConfig::class])
interface Client {
    @PostMapping(
        path = "/some/path", 
        consumes = [MediaType.APPLICATION_FORM_URLENCODED_VALUE])
    postComment(CommentFormDto formDto): responseDto
    ...
}
...
import feign.form.FormEncoder
@Configuration
class CustomConfig {
    @Bean
    fun formEncoder(): FormEncoder {
        return FormEncoder()
    }
}
...
import feign.form.FormProperty
data class CommentFormDto (
    @FormProperty("author_id")
    var authorId: Long
    @FormProperty("ids[]")
    var ids: List<Long>
)

只是一个额外的贡献...可以使用 Spring 抽象,即 org.springframework.util.MultiValueMap ,它没有其他依赖项(只有 spring-cloud-starter-openfeign)。

@PostMapping(value = "/your/path/here", 
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
YourDtoResponse formUrlEncodedEndpoint(MultiValueMap<String, Object> params);

这个有用的数据结构的语法非常简单,如下所示:

MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("param1", "Value 1");
params.add("param2", 2);
您必须

在 Feign 编码器中使用 FormEncoder 来获取 POST 中的 url-form 编码数据。

包括应用的依赖项:

专家:

<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");

在伪装界面中

@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

在 Kotlin 中测试: 对我有用的是:

  1. 创建假配置:
@Configuration
class FeignFormConfiguration {
    @Bean
    fun multipartFormEncoder(): Encoder {
        return SpringFormEncoder(SpringEncoder {
            HttpMessageConverters(
                RestTemplate().messageConverters
            )
        })
    }
}
  1. 在您的假客户端中:
@FeignClient(
    value = "client",
    url = "localhost:9091",
    configuration = [FeignFormConfiguration::class]
)
interface CoreClient {
    @RequestMapping(
        method = [RequestMethod.POST],
        value = ["/"],
        consumes = [MediaType.APPLICATION_FORM_URLENCODED_VALUE],
        produces = ["application/json"]
    )
    fun callback(@RequestBody form: Map<String, *>): AnyDTO?
}
  1. 使用假客户端:
// ----- other code --------
@Autowired
private lateinit var coreClient: CoreClient
fun methodName() {
  coreClient.callback(form)
}
// ----- other code --------
这对

我有用

@FeignClient(name = "${feign.repository.name}", url = "${feign.repository.url}")
public interface LoginRepository {
     @PostMapping(value = "${feign.repository.endpoint}", consumes = APPLICATION_FORM_URLENCODED_VALUE)
     LoginResponse signIn(@RequestBody Map<String, ?> form);
}

形式是Map<String, Object> loginCredentials = new HashMap<>();

对于Feign.Builder,我的工作没有JacksonEncoder,只有Feign FormEncoder:

将 FormEncoder 添加到您的 Feign.Builder:

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

我添加到pom的假装依赖项.xml:

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

pom.xml中的父项是:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.2</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

拉马南给出的假装界面:

@RequestLine("POST /submit/form")
@Headers("Content-Type: application/x-www-form-urlencoded")
void from (@Param("field1") String field1, @Param("field2") String field2);
public class CoreFeignConfiguration {
@Autowired
  private ObjectFactory<HttpMessageConverters> messageConverters;
  @Bean
  @Primary
  @Scope("prototype")
  Encoder feignFormEncoder() {
      return new FormEncoder(new SpringEncoder(this.messageConverters));
  }
  @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
  
  @Bean
  Logger logger() {
    return  new MyLogger();
  }
  private static class MyLogger extends Logger {
        @Override
        protected void log(String s, String s1, Object... objects) {
            System.out.println(String.format(s + s1, objects)); // Change me!
        }
  }

}

在界面中@FeignClient(name = "resource-service1", url = "NOT_USED", configuration = CoreFeignConfiguration.class)

公共接口 TestFc {

@RequestMapping( method=RequestMethod.POST,consumes = "application/x-www-form-urlencoded")
//@Headers("Content-Type: application/x-www-form-urlencoded")
ResponseEntity<String>  test(URI baseUrl,
        Map<String,?> request);

}

相关内容

  • 没有找到相关文章

最新更新