You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring REST API出现406错误:Could not find acceptable representation求助

Spring Web请求参数获取时出现406 Not Acceptable错误

错误信息

<status>406</status>
    <error>Not Acceptable</error>
    <trace>org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation&#xd;
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:315)&#xd;
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219)&#xd;
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)&#xd;
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135)&#xd;
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)&#xd;
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)&#xd;
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)&#xd;
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)&#xd;
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)&#xd;
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)&#xd;
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)&#xd;
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:670)&#xd;
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)&#xd;
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)&#xd;
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)&#xd;
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)&#xd;
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)&#xd;
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)&#xd;
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)&#xd;
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)&#xd;
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)&#xd;
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)&#xd;
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)&#xd;
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)&#xd;
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)&#xd;
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)&#xd;
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)&#xd;
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)&#xd;
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)&#xd;
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)&#xd;
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)&#xd;
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)&#xd;
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)&#xd;
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)&#xd;
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)&#xd;
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)&#xd;
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)&#xd;
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)&#xd;
    at java.base/java.lang.Thread.run(Thread.java:833)&#xd;
</trace>
    <message>Could not find acceptable representation</message>
    <path>/api/users</path>

已添加的Maven依赖

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

请求地址

http://localhost:8080/api/users?userID=1

相关代码

Controller类

@RestController
@EnableWebMvc
@RequestMapping("/api")
@Log4j2
public class UsersController {
    @Autowired
    UsersService service;

    @PostMapping("/users")
    public Users createU(@RequestBody UsersPostRequestBody ubody) {
        return service.save(ubody);
    }

    @ResponseBody
    @GetMapping(value = "/users")
    public ResponseEntity<UsersGetByIdResponseBody> findUById(@RequestParam Long userID) {
        return service.getUsersInfoById(userID);
    }
}

Service实现类

@Override
public ResponseEntity<UsersGetByIdResponseBody> getUsersInfoById(Long usersID) {
    Users user = repository.findById(usersID)
                                    .orElseThrow(() -> new NullPointerException("User not found."));

    UsersGetByIdResponseBody userResponse = new UsersGetByIdResponseBody(user.getUserID(), user.getUsername(), user.getReputation(),
                        user.getProfileImageURL(), user.getBannerImageURL(), user.getAboutMe(), user.getTag(), user.getAccountType());

    return ResponseEntity.ok(userResponse);
}

响应体类

@AllArgsConstructor
public class UsersGetByIdResponseBody {
    private Long userID;
    private String username;
    private Long reputation;
    private String profileImageURL;
    private String bannerImageURL;
    private String aboutMe;
    private String tag;
    private AccountTypeEnum accountType;
}

期望输出

{
    "userID": 1,
    "username": "john",
    "reputation": 0,
    "profileImageURL": null,
    "bannerImageURL": null,
    "aboutMe": null,
    "tag": null,
    "accountType": "DEFAULT"
}

问题说明

添加上述依赖后仅将错误信息格式改为XML,仍无法获取JSON格式的正常响应,期望返回UsersGetByIdResponseBody对象且状态码为200 OK。


解决方案

1. 修复响应体类的序列化问题

Jackson默认需要通过getter方法访问对象字段,当前UsersGetByIdResponseBody仅添加了@AllArgsConstructor,没有getter方法。可通过以下方式解决:

  • 给类添加@Data注解(Lombok),自动生成getter、setter等方法:
    @Data
    @AllArgsConstructor
    public class UsersGetByIdResponseBody {
        // 字段不变
    }
    
  • 手动为每个字段添加getter方法。

2. 移除冲突的Jackson依赖

同时引入codehaus.jackson和fasterxml.jackson会导致依赖冲突,Spring Boot默认使用fasterxml系列的Jackson,删除POM中的codehaus相关依赖:

<!-- 移除以下两个依赖 -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

3. 优化Controller配置

  • @RestController已经包含@ResponseBody,删除findUById方法上的@ResponseBody;
  • 在@GetMapping中指定produces = MediaType.APPLICATION_JSON_VALUE,强制返回JSON格式:
    @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UsersGetByIdResponseBody> findUById(@RequestParam Long userID) {
        return service.getUsersInfoById(userID);
    }
    

4. 确保枚举类可正确序列化

如果AccountTypeEnum是自定义枚举,添加@JsonValue注解确保Jackson将其序列化为字符串:

public enum AccountTypeEnum {
    DEFAULT, PREMIUM;

    @JsonValue
    @Override
    public String toString() {
        return name();
    }
}

5. 检查请求头的Accept字段

确保请求的Accept头设置为application/json,使用Postman等工具时直接选择JSON格式即可。


内容的提问来源于stack exchange,提问作者r1ddax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:25:19