У меня есть приложение Spring MVC 3.2, которое не принимает запрос JSON POST из браузера. Если я использую такой инструмент, как CocoaRest, все в порядке. Но когда я использую браузер или инструмент, как хром: //restclient/content/restclient.html тогда я получаюSpringMVC JSON неподдерживаемый тип
HTTP Status 415 -Сервер отказалась от этого запроса, так как запрос объект в формате, который не поддерживается запрошенный ресурс для запрошенного метода .
Вот моя конфигурация:
@Bean
public ContentNegotiationManagerFactoryBean contentNegotiationManager() {
Properties properties = new Properties();
properties.setProperty("xml", "application/xml");
properties.setProperty("json", "application/json");
properties.setProperty("html", "application/html");
ContentNegotiationManagerFactoryBean contentNegotiationManager = new ContentNegotiationManagerFactoryBean();
contentNegotiationManager.setFavorParameter(true);
contentNegotiationManager.setMediaTypes(properties);
contentNegotiationManager.setIgnoreAcceptHeader(true);
contentNegotiationManager.setDefaultContentType(MediaType.APPLICATION_JSON);
return contentNegotiationManager;
}
и мой ПОМ:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Вот мой контроллер:
@Transactional
@ResponseBody
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)public EmployeeDTO addEmployee(@PathVariable String officeName, @RequestBody @Valid final Employee employee,
BindingResult result) {
List<String> errors = new ArrayList<String>();
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
errors.add(error.getDefaultMessage());
}
throw new EmployeeSetupException(errors, "Employee could not be configured, please check your submitted values.");
}
...
}
Вот мой запрос:
{
"address" : {
"status" : null,
"city" : "Lakewood",
"addressId" : 1,
"seqId" : null,
"addressLine1" : "123 Maple Ave",
"zip" : "80111",
"addressLine2" : "Apt 101",
"zipLong" : null,
"addressLine3" : "room C ",
"state" : "CO"
},
"office" : null,
"licenseNumber" : "0987654321A",
"scheduleId" : null,
"user" : {
"status" : 1,
"userName" : "[email protected]",
"userRole" : {
"userRoleDescription" : "The person or entity that owns a particular practice, who has the highest level of authorization",
"userRoleDescriptionShort" : "Practice Owner",
"userRoleId" : 20
}
},
"firstName" : "Sid",
"ssn" : "111-22-3332",
"specialtyId" : null,
"lastName" : "Vicious",
"fullName" : null
}
Я прочитал несколько статей, в которых говорится, что установка содержимого заголовка в application/json или form сделает это. Но когда я устанавливал contentType для приложения/json и/или application/x-www-form-urlencoded, он все равно терпит неудачу в браузере. Я также попытался отправить через jQuery, но я получаю тот же результат.
, если я изменю контроллер от:
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
в
@RequestMapping(method = RequestMethod.POST)
тогда я получаю это, когда я отправить через браузер:
Received Exception Content type 'text/plain;charset=UTF-8' not supported
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:149)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:180)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:95)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
Это не имеет смысла поскольку клиент Chrome Chrome chrome: //restclient/content/restclient.html показывает ContentType приложения/json для запроса.
Если кто-то знает, что может быть не так, я, безусловно, буду признателен за помощь.
Вы пробовали настройки (в конф файле): 'contentNegotiationManager.setIgnoreAcceptHeader (ложь),' – nickdos
Да, я изменил 'contentNegotiationManager.setIgnoreAcceptHeader (ложь)' до 'contentNegotiationManager.setIgnoreAcceptHeader (правда)', но я до сих пор получить то же сообщение «415 content message» – sonoerin
Я предполагал, что он должен быть ложным (ваш код выше имеет его как истинный) - вы хотите, чтобы он использовал заголовок accept и не полагался на расширение файла, чтобы определить тип контента (эффективно, когда он установлен на правда). Но похоже, что вы пробовали его с обоими значениями. – nickdos