Spring REST Docs报错:No content to map due to end-of-input 求助
问题排查与解决方案
这个错误的核心原因很明确:Spring REST Docs在生成links代码片段时,尝试从响应体里解析HAL格式的链接,但实际响应体是空的(或者根本不是有效的HAL结构),导致Jackson无法完成映射操作。下面分场景给出具体的排查和解决步骤:
1. 先确认控制器是否返回了带HAL链接的响应体
你的POST接口大概率只返回了状态码,没返回符合HAL规范的资源对象。REST Docs的halLinks()要求响应体必须包含_links字段(HAL格式的核心标识),否则就会因为找不到可解析的内容报错。
解决办法:
修改控制器方法,用Spring HATEOAS的EntityModel(或旧版的Resource)包装你的实体,并手动添加所需链接:
import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; // ... @PostMapping("/hostel") public ResponseEntity<EntityModel<Hostel>> createHostel(@RequestBody Hostel hostel) { Hostel savedHostel = hostelService.save(hostel); // 生成测试中指定的"ld:GetHostel"链接 Link getHostelLink = WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder.methodOn(HostelController.class).getHostel(savedHostel.getId()) ).withRel("ld:GetHostel"); // 用EntityModel包装实体并注入链接 EntityModel<Hostel> resource = EntityModel.of(savedHostel, getHostelLink); return ResponseEntity.ok(resource); }
2. 检查是否缺少Spring HATEOAS依赖
如果项目里没引入Spring HATEOAS的starter,Spring Boot无法自动配置HAL格式的消息转换器,响应也就无法序列化为符合要求的HAL结构。
解决办法:
根据你的构建工具添加依赖:
- Maven(
pom.xml):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency>
- Gradle(
build.gradle):
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
3. 快速验证响应体是否正常
可以先临时注释掉测试代码里的links片段,运行测试看看结果:
.andDo(document("create-hostel", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), // 临时注释links部分,先验证基础流程 // links(halLinks(), // linkWithRel("ld:GetHostel").description("Get Hostel"), // linkWithRel("curies").description("Documentation")), requestFields( fieldWithPath("description").description("The description"), fieldWithPath("name").description("The name"), fieldWithPath("id").description("The id") ) ));
如果注释后测试通过,说明问题确实出在HAL链接的解析上;如果还是报错,那就要先排查控制器是否正常返回响应体了。
4. 关于curies链接的额外说明
测试中你指定了linkWithRel("curies"),但如果控制器没有手动添加这个链接,也可能引发解析异常。你可以二选一:
- 在控制器里补充添加curies链接
- 从测试的
links配置中移除linkWithRel("curies")(如果你的API不需要这个规范链接的话)
内容的提问来源于stack exchange,提问作者Sandro Rey
相关产品推荐
相关产品推荐

