我使用的是Spring Boot 1.5.2,我有一个简单的REST控制器,如下所示:
@RestController
@RequestMapping
public class UserJWTController {
@Inject
private TokenProvider tokenProvider;
@Inject
private AuthenticationManager authenticationManager;
@PostMapping(value = "/authenticate", produces = Version.V1_JSON_VALUE, consumes = Version.V1_JSON_VALUE)
public ResponseEntity<?> authenticate(final @RequestBody LoginVM loginVM, HttpServletResponse response) {
}
}
常量,
public final class Constants {
// API versioning
public static final String API_VERSION_MEDIA_TYPE = "application/vnd.test.onboarding";
public static final String JSON_MIME_TYPE = "json";
private Constants() {
}
}
版,
public class Version {
// All versions defined here
public static final String V1_JSON_VALUE = Constants.API_VERSION_MEDIA_TYPE + ".v1+" + Constants.JSON_MIME_TYPE;
public static final MediaType V1_JSON = MediaType.valueOf(V1_JSON_VALUE);
public static final String V2_JSON_VALUE = Constants.API_VERSION_MEDIA_TYPE + ".v2+" + Constants.JSON_MIME_TYPE;
public static final MediaType V2_JSON = MediaType.valueOf(V2_JSON_VALUE);
}
但是,这似乎引发了以下错误,
WARN 37805 --- [ XNIO-2 task-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/vnd.test.onboarding.1.0+json' not supported
我正在使用的卷发
curl -X POST "http://localhost:8080/api/authenticate" -H "Accepts: application/vnd.test.onboarding.1.0+json" -H "Content-Type: application/vnd.test.onboarding.1.0+json" -d '{"usernme":"test", "password":"password"}'
{
"status" : 415,
"error" : "Unsupported Media Type",
"exception" : "org.springframework.web.HttpMediaTypeNotSupportedException",
"message" : "Unsupported Media Type",
"path" : "/api/authenticate"
}
我不确定为什么自定义媒体类型会导致HttpMediaTypeNotSupportedException
。 会以为Spring Boot应该能够自动处理这个问题。
更新
消息转换器已注册,
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
jsonConverter.setSupportedMediaTypes(Arrays.asList(Version.V1_JSON));
jsonConverter.setSupportedMediaTypes(Arrays.asList(Version.V2_JSON));
return jsonConverter;
}
不知道我怎么错过了它,但是结果是版本和我要求的Accept
标头不正确。
它应该是,
curl -X POST "http://localhost:8080/api/authenticate" -H "Accept: application/vnd.test.onboarding.1v+json" -H "Content-Type: application/vnd.test.onboarding.1v+json" -d '{"usernme":"test", "password":"password"}'
我还必须指定以下内容协商,
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true)
.favorParameter(false)
.ignoreAcceptHeader(false)
.useJaf(false)
.defaultContentType(MediaType.APPLICATION_JSON);
}
而且我不需要mappingJackson2HttpMessageConverter