弹簧靴 406 "Not Acceptable"



我正在尝试使用版本为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"
}

谁能帮忙?

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

  1. 添加杰克逊
  2. 使用@JsonInclude(JsonInclude.Include.NON_NULL( @JsonIgnoreProperties(忽略未知 = true(实现
  3. 序列 化

但在 DTO 中缺少@Getter。

你可以实现过滤器接口

并设置标题与所有方法都可以接受

@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() {}

}

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

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

请确保您有这些jar并在邮递员标题中使用标题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>

我也遇到了406不可接受的错误。经过调查,我发现这是由控制器方法返回无效的 bean 对象引起的。

我试图返回的对象

  • java.lang.Object
  • 没有任何属性的类

它们都会产生 HTTP 406 错误。

这可能是一个棘手的问题。

406 表示不可接受

现在我们在返回错误响应时遇到了这个问题。我们的错误 pojo 类正在实现Response接口

public class ErrorResponse implements Response {
private final String error;
private final ErrorDetails details;
}

下面是生成并返回响应实体响应的代码

private ResponseEntity<ErrorResponse> buildErrorResponse(final String errorMessage, final ErrorDetails error,
final HttpStatus httpStatus) {
return ResponseEntity.status(httpStatus).body(ErrorResponse.builder().error(errorMessage).details(error).build());
}

当我们在邮递员中对此进行测试时,我们了解到响应不完整且是有效的 json。

就像下面一样

data: { error: "Some Error", details : {}}

其中有效的 JSON 响应如下所示(因为数据是来自包装正文的响应实体的包装器(

{ error: "Some Error", details : {}}

因此,我们代码中的问题是我们没有设置适当的标头。所以固定代码如下所示。.contentType(APPLICATION_JSON(设法将其转换为有效的可接受响应

private ResponseEntity<ErrorResponse> buildErrorResponse(final String errorMessage, final ErrorDetails error,
final HttpStatus httpStatus) {
return ResponseEntity.status(httpStatus).contentType(APPLICATION_JSON).body(ErrorResponse.builder().error(errorMessage).details(error).build());
}

最新更新