zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    在springboot程序中自定义注解和反序列化实现
    文章相似度算法调研
    HTTP协议详解
    prototype.js 让你更深入的了解javascript的面向对象特性(转)
    ajax框架汇总
    prototype源码分析(转)
    c#中静态成员和实例成员(转)
    .NET中IDisposable接口的基本使用 (转)
    sql server 数据库优化(转)
    ADO.NET事物
  • 原文地址:https://www.cnblogs.com/lori/p/14440827.html
Copyright © 2011-2022 走看看