Announcement Announcement Module
Collapse
No announcement yet.
Return JSON from RestTemplate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Return JSON from RestTemplate

    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:

    Code:
    ...
    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");
    }
    ...
    The line restTemplate.postForObject(...) returns org.springframework.web.client.HttpClientErrorExce ption: 415 Unsupported Media Type


    Where is my mistake?

    My spring config 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>
    MappingJacksonJsonPutinView 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;
    	}
    
    }
    Finally, my controller is:

    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);
    	}
    }
    BTW, restTemplate.getForObject(...) works well.

    Thanks in advance.

    Johnny

  • #2
    Hi guys, any idea?

    Comment


    • #3
      Hi,

      I guess you get this error because you don't set the "Accept" header in the request, so on the server side the request is not dispatched as you expect.

      I encountered a similar problem trying to use RestTemplate, and apparently it is not yet possible to set the request headers (please correct me if I'm wrong about that), so I used Apache HTTP Client instead.

      Another option is to use suffix as an alternative to the "Accept" header on the server side, for example use ".json" URL suffix to act the same as "text/json" accept header as demonstrated here: http://static.springsource.org/sprin...epresentations

      Comment


      • #4
        Hi guznik,

        We tried for the same but not able to find the solution so, requesting to provide the changes that are to be done at the server side as well as the client side.


        Thanks!
        Basha

        Comment


        • #5
          RestTemplate

          Hi Guys,

          can you plz help me out for below isuues.

          * can we pass more than one request object (userdefined object not predifined)
          through postForObject of restTemplate? if yes plz let me know.

          * i am using restTemplate.postForObject(url,myProduct,DefaultSt ock.class);
          with MappingJacksonMessageConverter and sending myProduct (userdefined object) as a request object.
          In controller i am receiving this object as String i.e Json object and then i need to convert this json object to java object below is the code in controller
          @RequestMapping(method = RequestMethod.POST , value="/stock/", headers="Accept=application/json")
          public @ResponseBody DefaultStock getDecreaseStock(@RequestBody String product)

          my question can i receive this myProduct object as a product instead of stiring ?
          like this
          @RequestBody Product product not like this @RequestBody String product

          Thanks@Regards,
          Manoj

          Comment

          Working...
          X