起因
对于微服务之后发请求,目前使用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);
结果的响应
愿与诸君共进步,大量的面试题及答案还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系,可以微信搜索539413949获取,最后祝大家都能拿到自己心仪的offer