调用Courses微服务GET接口遇405错误求助
问题排查:Feign调用GET接口返回405错误码
问题根源
405错误的核心原因是HTTP GET请求携带请求体(@RequestBody)不符合通用规范。Spring MVC默认会拒绝这类请求——GET请求设计用于获取资源,通常不包含请求体,大部分服务器也不支持处理带请求体的GET请求。你其他GET接口(如/courses/course/{id})能正常工作,是因为它们使用路径参数(@PathVariable)传递数据,没有携带请求体,符合GET请求规范。
解决方案
方案1:改用POST请求(推荐)
POST请求天然支持携带请求体,适合批量传递参数的场景,修改如下:
Purchases微服务Feign接口:
@FeignClient(value = "COURSES", configuration = {FeignConfig.class}) public interface CourseService { @PostMapping("/courses/all-by-id") CoursesByIdResponse getAllByCourseIds(@RequestBody CourseIdsRequest courseIds); }
Courses微服务Controller:
@RestController() @CrossOrigin(origins = "*", maxAge = 3600) public class CourseController { private final CoursePaginatedService courseService; public CourseController(@Qualifier("paginatedService") CoursePaginatedService courseService) { this.courseService = courseService; } @PostMapping("/courses/all-by-id") public ResponseEntity<CoursesByIdResponse> getAllByCourseIds(@RequestBody CourseIdsRequest courseIds){ return ResponseEntity.ok(courseService.getAllByCourseIds(courseIds.getCourseIds())); } }
方案2:坚持用GET请求(调整参数传递方式)
如果业务上必须使用GET,需将参数改为请求参数传递,修改如下:
Purchases微服务Feign接口:
@FeignClient(value = "COURSES", configuration = {FeignConfig.class}) public interface CourseService { @GetMapping("/courses/all-by-id") CoursesByIdResponse getAllByCourseIds(@RequestParam("courseIds") List<Long> courseIds); }
Courses微服务Controller:
@RestController() @CrossOrigin(origins = "*", maxAge = 3600) public class CourseController { private final CoursePaginatedService courseService; public CourseController(@Qualifier("paginatedService") CoursePaginatedService courseService) { this.courseService = courseService; } @GetMapping("/courses/all-by-id") public ResponseEntity<CoursesByIdResponse> getAllByCourseIds(@RequestParam("courseIds") List<Long> courseIds){ return ResponseEntity.ok(courseService.getAllByCourseIds(courseIds)); } }
这种方式下,请求URL会变成类似/courses/all-by-id?courseIds=1&courseIds=2&courseIds=3,符合GET请求的参数传递规范。
内容的提问来源于stack exchange,提问作者Balsa Stevovic
相关产品推荐
相关产品推荐

