首页 > 解决方案 > 在 Feign Client 中使用 spring form 编码器时,请求正文未正确编码和隐藏

问题描述

我已经为https://github.com/OpenFeign/feign-form中提到的 spring open feign 添加了必要的依赖项,并遵循了 feign-client 的上述配置。

每当我发送内容类型为 application/x-www-form-urlencoded 的 post 请求时。请求正文未正确生成。

电子邮件客户端.java

@FeignClient(name = "email", url = "localhost:3000",
     configuration = EmailClientConfiguration.class)

public interface EmailClient {

    @PostMapping(value = "/email/send")
    ResponseDto sendEmail(@RequestBody Map<String, String> requestBody);
        
}

这是我的客户端配置类:

public class EmailClientConfiguration  {
    
    @Bean
    public RequestInterceptor requestInterceptor(Account<Account> account) {
        return template -> {
             template.header("Content-Type", "application/x-www-form-urlencoded");
        };
    }
    
    @Bean
    public OkHttpClient client() {
        return new OkHttpClient();
    }
    
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
    
    @Bean
    public Decoder feignDecoder() {
        return new JacksonDecoder();
    }
    
    @Bean
    public Encoder feignFormEncoder () {
        return new SpringFormEncoder(new JacksonEncoder());
    }
}
    
    
Map<String, String> requestBody = new HashMap<>();
requestBody.put("username", "xyz");
requestBody.put("email", "xyz@gmail.com");
requestBody.put("key", "xxx");

当我在接口中调用 sendEmail 方法时,请求者标头设置正确,但请求正文发送为

{"{\n  \"key\" : \"xxx\",\n  \"email\" : \"xyz@gmail.com\",\n  \"username\" : \"xyz\"\n}"

有人可以帮忙吗?为什么请求正文是这样发送的。尽管 content-type 是application/x-www-form-urlencoded.

标签: javaspringspring-bootspring-cloud-feign

解决方案


添加消耗后它工作正常。

@FeignClient(name = "email", url = "localhost:3000",
     configuration = EmailClientConfiguration.class)

public interface EmailClient {

    @PostMapping(value = "/email/send", consumes = "application/x-www-form-urlencoded")
    ResponseDto sendEmail(@RequestBody Map<String, String> requestBody);
    
}

推荐阅读