Controller接口响应Content-Type为text/html而非application/json问题求助
问题描述
我在编写Controller测试用例时碰到一个问题:接口预期返回application/json类型的响应,但实际收到的Content-Type却是text/html。我已经在@RequestMapping注解中添加了produces属性,测试代码里也设置了请求的Content-Type头部,但问题依旧存在。
排查与解决步骤
1. 检查是否有未捕获的异常
如果Controller方法执行时抛出未处理的异常,Spring会默认返回HTML格式的错误页面,导致Content-Type变为text/html。
- 查看堆栈日志,确认是否有异常抛出(比如空指针、参数绑定失败等)。
- 用
@RestControllerAdvice实现全局异常捕获,确保异常返回JSON格式:
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<Map<String, Object>> handleException(Exception e) { Map<String, Object> error = new HashMap<>(); error.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value()); error.put("message", e.getMessage()); return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); } }
2. 确认produces配置正确性
保证@RequestMapping(或@GetMapping/@PostMapping)的produces属性准确配置为application/json,且返回值是可序列化的对象:
@GetMapping(value = "/api/user", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<User> getUserInfo() { User user = new User("test", 20); return ResponseEntity.ok(user); }
注意:如果方法直接返回String,Spring会默认返回text/plain,需确保返回对象而非字符串。
3. 测试代码中添加Accept请求头
测试时不仅要设置请求的Content-Type,还要通过Accept头告知服务器客户端期望接收JSON:
mockMvc.perform(get("/api/user") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) // 必须添加此配置 .andExpect(content().contentType(MediaType.APPLICATION_JSON));
4. 排查拦截器/过滤器对响应的修改
项目中的拦截器或过滤器可能会篡改响应头:
- 检查是否有拦截器在处理流程中修改了Content-Type。
- 如果用了Spring Security,确认认证/授权失败时是否返回JSON而非默认的HTML页面。
5. 验证返回对象的序列化能力
如果返回对象无法被Jackson正常序列化,Spring会返回错误页面:
- 确保返回对象有无参构造函数,字段有对应的getter方法。
- 检查
jackson-databind依赖是否存在(Spring Boot starter默认包含,若手动排除需重新引入)。
6. 关闭错误页面白标配置
若项目中存在自定义错误页面(如error.html),发生错误时Spring会优先返回该页面,可通过配置关闭:
在application.properties中添加:
server.error.whitelabel.enabled=false
内容的提问来源于stack exchange,提问作者Jcoder
相关产品推荐
相关产品推荐

