通過SpringCloud Feign 調用其他項目或微服務的接口方法時報Request method ‘POST‘ not supported 的錯誤:
問題出現原因:
- 可能的原因是 Feign 默認使用的請求方法為 POST,而不是 GET。
- 另外也有可能是由于消費方法和接口方法使用的注解不正確;如果 Feign 代理的是 get 請求,則每個參數必須帶上 @RequestParam 注解,否則會報 POST not supported
- 可能是SpringCloud原生的Feign,可以考慮使用OpenFeign
- 可以考慮修改使用feign默認配置的方法默認使用post
- 通過feign調用get請求時,如果接口參數含有POJO時,可能會出現 ‘POST’ not supported
解決方法
-
在Feign代理接口方法處使用 @RequestMapping 替代 @GetMapping: 嘗試使用 @RequestMapping 注解代替 @GetMapping 注解,顯式指定請求方法為 GET。示例代碼如下:
@FeignClient(name = "your-service-name") public interface YourFeignClient {@RequestMapping(method = RequestMethod.GET, value = "/your/api/path")String yourGetMethod(); }
-
另外也有可能是由于消費方法和接口方法使用的注解不正確;
@RequestBody-------------> @PostMapping
@RequestParam 、@PathVariable------@GetMapping@GetMapping("/user/list")List<userInfo> list(@PathVariable List<String> userIdList);
-
在pom.xml文件引入openfeign
<!-- 在 pom 中添加依賴--><dependency><groupId>io.github.openfeign</groupId><artifactId>feign-httpclient</artifactId></dependency>
-
自定義 FeignClient 的配置: 在 FeignClient 的配置類中,可以自定義 Feign 的配置,指定 FeignClient 默認的請求方法為 GET。示例代碼如下:
@Configuration public class FeignConfiguration {@Beanpublic RequestInterceptor requestInterceptor() {return new RequestInterceptor() {@Overridepublic void apply(RequestTemplate template) {template.method("GET");}};} }
-
還有一種情況,涉及到實體類的情況,如果接口參數含有POJO,feign調用入參是POJO的GET請求時,會往body里設置參數,而因為發現body里有數據,就會自動將get請求轉為post,feign版本在2.0以上,在消費方法的實體類對象參數前新增@SpringQueryMap注解即可
@FeignClient("user") public class userList{@GetMapping(path="/your/api/path")String queryUser(@SpringQueryMap User user); }