即使内容类型设置为 application/x-www-form-urlencoded,请求正文仍作为 json 发送

问题描述

这与我 (Request Body is not properly encoded and hidden when using spring form encoder in Feign Client) 提出的现有 Spring Boot 问题有关。

根据this question,我们可以在标头中添加内容类型,也可以在请求映射期间将其自身添加为消费。

所以我所做的是在客户端配置类的标题中添加内容类型

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());
    }
}

并且我在标题中看到内容类型在发送请求时正确设置为 application/x-www-form-urlencoded。但是请求体仍然以json格式发送,也没有隐藏。

请求正文:

Map<String,String> requestBody = new HashMap<>();
requestBody.put("username","xyz");
requestBody.put("email","[email protected]");
requestBody.put("key","xxx");

服务器端收到的请求正文:

{"{\n  \"key\" : \"xxx\",\n  \"email\" : \"[email protected]\",\n  \"username\" : \"xyz\"\n}"

当我在请求映射中将消费添加为 application/x-www-form-urlencoded

@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);
    
}

它工作正常(请求正文隐藏在服务器端并且也正确编码)。当我删除配置类中的标头并仅添加消耗时,它可以正常工作而没有任何问题,但反之亦然有这个问题。

我在互联网上搜索了这个,但找不到任何答案。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)