【问题标题】:Spring Boot 406 "Not Acceptable"Spring Boot 406“不可接受”
【发布时间】:2022-03-02 22:27:29
【问题描述】:

我正在尝试使用版本为 2.0.5.RELEASE 的 Spring Boot 构建 RESTful API。这是我的控制器:

// Just for test
@RestController
public class LoginController {

    @RequestMapping(value = "/user/login",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> login(@RequestParam(name = "username") String username,
                                   @RequestParam(name = "password") String password) {

        ResponseEntity<RESTResponse> response = null;

        if(username.equals("123") && password.equals("123")){
            // success
            response = new ResponseEntity<>(RESTResponse.generateResponse(
                    null, "successful", "Log in successfully."), HttpStatus.OK);
        } else {
            // failed
            response = new ResponseEntity<>(RESTResponse.generateResponse(
                    null, "failed", "Your username or password is incorrect."), HttpStatus.OK);
        }

        return response;
    }

}

这是 Spring MVC 配置类:

@Configuration
public class MyMvcConfig implements WebMvcConfigurer{

    /**
     * CORS configuration
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(ALL)
                .allowedMethods(ALL)
                .allowedHeaders(ALL)
                .allowCredentials(true);
    }


}

控制器应该响应 JSON 数据。我使用 Postman 来测试控制器。控制器可以接收请求参数并正常工作,但邮递员得到了一个奇怪的响应:

{
    "timestamp": "2018-09-16T05:55:14.860+0000",
    "status": 406,
    "error": "Not Acceptable",
    "message": "Could not find acceptable representation",
    "path": "/api/user/login"
}

有人可以帮忙吗?

【问题讨论】:

    标签: rest spring-boot


    【解决方案1】:

    你可以实现Filter接口

    并设置header,所有方法都可以接受

    @Component
    public class CORSFilter implements Filter{
    
    
         static Logger logger = LoggerFactory.getLogger(CORSFilter.class);
    
         @Override
            public void init(FilterConfig filterConfig) throws ServletException {
            }
    
            @Override
            public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                  HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
                chain.doFilter(request, response);
                logger.info(request.getRemoteAddr());
            }
    
            public void destroy() {}
    
    
    
    }
    

    【讨论】:

      【解决方案2】:

      确保您在邮递员标题中使用Accept: application/json

      如果完成上述操作,请尝试在方法签名中添加 consumes= MediaType.APPLICATION_JSON_VALUE 以及生成。

      【讨论】:

      • 我试过了,又出现了一个问题。 Java 收到警告:Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'username' is not present]
      • 是的,这是因为请求不包含请求参数。因此请确保您在邮递员请求中添加名为 username 的参数。
      【解决方案3】:

      确保你有这些 jars 并在邮递员标题中使用 Header Accept: application/json

      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.4.1</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.4.1.1</version>
      </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>
      

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题并尝试过

        1. 添加杰克逊
        2. 使用@JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true)实现
        3. 可序列化

        但在 dto 中缺少 @Getter。

        【讨论】:

          猜你喜欢
          • 2019-03-11
          • 1970-01-01
          • 2013-04-26
          • 2013-03-18
          • 1970-01-01
          • 2019-04-30
          • 2016-08-11
          • 2019-11-17
          相关资源
          最近更新 更多