springcloud~feign POST form-url-encoded data

起因

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

一般,一个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);

结果的响应
118538-20210224130930548-983481015.png

愿与诸君共进步,大量的面试题及答案还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系,可以微信搜索539413949获取,最后祝大家都能拿到自己心仪的offer

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值