Dear all,
help me to understand how I should pass any object to restTemplate.post...() to send a json request to controller.
Here is a test method:
The line restTemplate.postForObject(...) returns org.springframework.web.client.HttpClientErrorExce ption: 415 Unsupported Media TypeCode:... private RestTemplate restTemplate; @BeforeClass public void configure() { restTemplate = new RestTemplate(); List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>(); list.add(new MappingJacksonHttpMessageConverter()); restTemplate.setMessageConverters(list); } ... @Test public void post() { Person person = new Person(); person.setName("Mr. Putin"); Person res = restTemplate.postForObject("http://localhost:8080/rest-json/rest/person", person, Person.class); Assert.assertEquals(res.getName(), "Mr. Putin"); } ...
Where is my mistake?
My spring config is:
MappingJacksonJsonPutinView is:Code:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="org.putin.rest.controller" /> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean id="jsonView" class="org.putin.rest.view.MappingJacksonJsonPutinView" /> </beans>
Finally, my controller is:Code:public class MappingJacksonJsonPutinView extends MappingJacksonJsonView { @SuppressWarnings("unchecked") @Override protected Object filterModel(Map<String, Object> model) { Object result = super.filterModel(model); if (!(result instanceof Map)) { return result; } Map map = (Map) result; if (map.size() == 1) { return map.values().toArray()[0]; } return map; } }
BTW, restTemplate.getForObject(...) works well.Code:@Controller public class PersonController { private Logger log = LoggerFactory.getLogger(this.getClass().getName()); @RequestMapping(method=RequestMethod.POST, value="/person") public ModelAndView post(@RequestBody Person person) { log.info("Received person: " + person.toString()); return new ModelAndView("jsonView").addObject(person); } }
Thanks in advance.
Johnny



Reply With Quote
