• 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

  • 相关阅读:
    LinkLabel控件使用
    读取mysql代码片段
    设置点风格
    C# List 用法
    图片焦点图切换效果
    dreamweaver 泛泛之谈
    js 之for..in、表单及事件触发
    实现省份查询 功能
    input类主要是
    js (1)
  • 原文地址:https://www.cnblogs.com/lori/p/14440827.html
Copyright © 2020-2023  润新知