Spring Boot重定向至指定外部URL时出现MessageBodyWriter错误排查
解决Spring Boot返回RedirectView时的MessageBodyWriter错误
你在开发应用时,第三方服务登录后调用Spring Boot后端接口,期望重定向到Angular应用,但返回错误:
Could not find MessageBodyWriter for response object of type: org.springframework.web.servlet.view.RedirectView of media type: application/octet-stream
问题根源在于你的控制器混合了**JAX-RS注解(@Path、@POST、@FormParam等)**和Spring MVC的@Controller、RedirectView。JAX-RS的处理机制不识别Spring MVC的RedirectView类型,因此无法找到对应的消息转换器处理响应。
以下是两种可行的解决方案:
方案一:统一使用Spring MVC注解
将JAX-RS注解替换为Spring MVC的对应注解,让Spring MVC接管请求处理,即可正确解析RedirectView。
修改后的接口代码:
@Controller @RequestMapping("/login") public interface LoginApi { @PostMapping @Consumes("application/x-www-form-urlencoded") RedirectView login(@RequestParam("idToken") String idToken, @RequestParam("timestamp") String timestamp, @RequestParam("mac") String mac, HttpServletRequest httpRequest); }
实现类代码无需改动(Spring MVC会自动处理HttpServletRequest等上下文对象):
@Component public class LoginApiImpl implements LoginApi { private static final Logger LOG = LoggerFactory.getLogger(LoginApiImpl.class); @Override public RedirectView login(String idToken, String timestamp, String mac, HttpServletRequest httpRequest){ LOG.info("idToken: " + idToken + " timestamp: " + timestamp + " mac: " + mac); // 注意:重定向URL必须包含协议(http/https),否则会被当作相对路径 return new RedirectView("https://www.google.com") ; } }
方案二:继续使用JAX-RS,返回Response对象
如果要保留JAX-RS注解,不要返回Spring的RedirectView,而是使用JAX-RS的Response.seeOther()构建重定向响应。
修改后的接口代码:
@Path("/login") @Controller public interface LoginApi { @POST @Consumes({ "application/x-www-form-urlencoded" }) Response login(@FormParam(value = "idToken") String idToken, @FormParam(value = "timestamp") String timestamp, @FormParam(value = "mac") String mac, @Context SecurityContext securityContext, @Context HttpHeaders httpHeaders , @Context HttpServletRequest httpRequest); }
实现类代码:
@Component public class LoginApiImpl implements LoginApi { private static final Logger LOG = LoggerFactory.getLogger(LoginApiImpl.class); @Override public Response login(String idToken, String timestamp, String mac, @Context SecurityContext securityContext, @Context HttpHeaders httpHeaders, @Context HttpServletRequest httpRequest){ LOG.info("idToken: " + idToken + " timestamp: " + timestamp + " mac: " + mac); URI redirectUri = URI.create("https://www.google.com"); return Response.seeOther(redirectUri).build(); } }
关键注意事项
- 重定向URL必须包含协议(http/https),否则会被解析为当前请求的相对路径,导致重定向失败。
- 若选择JAX-RS方案,需确保Spring Boot项目已正确配置JAX-RS实现(如Jersey或RESTEasy)。
内容的提问来源于stack exchange,提问作者CodeRoch
相关产品推荐
相关产品推荐

