springcloud~feign POST form-url-encoded data

起因

对于微服务之后发请求,目前使用feign是比较多的,对外部服务也是同样支持的,有时间我们会有这样的情况,post请求时,不是使用的json raw的方式,而是使用了application/x-www-form-urlencoded这种方式,对于feign来说,这种方法的post默认是不被支持的,我们需要对feign进行一个扩展。

参考

https://stackoverflow.com/questions/61901362/feignclient-create-post-with-application-x-www-form-urlencoded-body
一般,一个POST的请求是这样的,它采用application/x-www-form-urlencoded的方式进行提交

curl -X POST \
  https://auth.beyondtime-stage.io/auth/realms/master/protocol/openid-connect/token \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -d 'username=admin&password=pass123&client_id=admin-cli&grant_type=password'

解决方案

添加编码转换器

    /**
     * 转换器.
     */
   @Component
    public class FeignConfiguration {
        @Bean
        Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> converters) {
            return new SpringFormEncoder(new SpringEncoder(converters));
        }
    }

feigenClient的post方式

@FeignClient(name = "keycloak", url = "http://192.168.4.26:8080/auth", configuration = FeignConfiguration .class)
public interface KcUserClient {

    @RequestMapping(value = "/realms/demo/protocol/openid-connect/token",
            method = RequestMethod.POST,
            consumes = "application/x-www-form-urlencoded")
    KeycloakAccessToken login(@RequestBody AuthTokenRequest authTokenRequest);
}

调用

AuthTokenRequest authTokenRequest = new AuthTokenRequest();
authTokenRequest.setClient_id("sms");
authTokenRequest.setGrant_type("password");
authTokenRequest.setPassword("123456");
authTokenRequest.setUsername("test");
authTokenRequest.setClient_secret("877e6236-2326-4837-bdaa-94ec61a95526");
var result=kcUserClient.login(authTokenRequest);

结果的响应
1

posted @   张占岭  阅读(1788)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2017-02-24 RabbitMQ~消息的产生和管理(15672)
2017-02-24 RabbitMQ~开篇与环境部署
2016-02-24 知方可补不足~SQL为大数据引入分区表
2016-02-24 实时监控Cat之旅~介绍与自定义类型在哪里
2012-02-24 C#代码是更具艺术性的,选择她,因为喜欢她
2012-02-24 MVC中业务层是否应该有个基类?它有什么作用?
点击右上角即可分享
微信分享提示