Announcement Announcement Module
Collapse
No announcement yet.
Post request via RestTemplate in json Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Post request via RestTemplate in json

    Hello guys,

    I didn't find any example how to solve my problem, so I want to ask you for help. I can't simply send POST request using RestTemplate object in JSON

    Every time I get org. springframework.web.client.HttpClientErrorExceptio n: 415 Unsupported Media Type

    I use RestTemplate in this way:
    Code:
    ...
    restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
    list.add(new MappingJacksonHttpMessageConverter());
    restTemplate.setMessageConverters(list);
    ...
    Payment payment= new Payment("Aa4bhs");
    Payment res = restTemplate.postForObject("http://localhost:8080/aurest/rest/payment", payment, Payment.class);
    My controller is:
    Code:
    ...
    @RequestMapping(method=RequestMethod.POST, value="/payment")
    public ModelAndView post(@RequestBody Payment payment) {
    	...
    	return new ModelAndView("jsonView").addObject(payment);
    }
    ...

    Where is my fault?

  • #2
    I can't simply send POST request using RestTemplate object in JSON
    ..

    Comment


    • #3
      Originally posted by Bret Lee View Post
      I can't simply send POST request using RestTemplate object in JSON
      ..
      excuse me, I don't understand your answer...

      Comment


      • #5
        You are telling the RestTemplate you expect a Payment as the return type:

        Code:
        restTemplate.postForObject("http://localhost:8080/aurest/rest/payment", payment, Payment.class);
        But your controller method returns a ModelAndView:

        Code:
        public ModelAndView post(@RequestBody Payment payment) {...}
        You also need to return the "payment" as @ResponseBody. Try doing something like this:

        Code:
        @RequestMapping(method=RequestMethod.POST, value="/payment")
        public @ResponseBody Payment post(@RequestBody Payment payment) {
            //do something with payment
            paymentService.postPayment( payment );
        
            return payment;
        }

        Comment


        • #6
          Here is a little example I got working.

          On the server side
          The controller:
          Code:
          @RequestMapping( value="/user/save", method=RequestMethod.POST, consumes="application/json" )
          public @ResponseBody User saveUser( @RequestBody User user ) {
          		
              userService.saveUser( user );
          		
              return user;
          
          }
          servlet-context.xml:
          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:mvc="http://www.springframework.org/schema/mvc"
          	xmlns:context="http://www.springframework.org/schema/context"
          	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
          		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
          
          	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
          	
          	<!-- Enables the Spring MVC @Controller programming model -->
          	<mvc:annotation-driven />
          
                       <!-- Scan for stereotype annotations-->
          	<context:component-scan base-package="com.rest.server" />
          	
          	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
          	<mvc:resources mapping="/resources/**" location="/resources/" />
          
          	<!-- Forwards requests to the "/" resource to the "welcome" view -->
          	<mvc:view-controller path="/" view-name="home"/>
          	
          	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
          	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          	    <property name="prefix" value="/WEB-INF/views/" />
          	    <property name="suffix" value=".jsp" />
          	</bean>
          	
          	<!-- Register JSON Converter for RESTful Web Service -->
          	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
              	    <property name="messageConverters">
                  	        <list>
                  	            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
                 	        </list>
             	    </property>
          	</bean>
          
          	<!-- Http Json MessageConverter -->
          	<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
             	    <property name="supportedMediaTypes" value="application/json" />
          	</bean>
          	
          </beans>
          On the client side
          The test:
          Code:
          package com.rest.client.test;
          
          import static org.junit.Assert.assertNotNull;
          import static org.junit.Assert.assertEquals;
          
          import org.junit.Test;
          import org.junit.runner.RunWith;
          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.http.HttpEntity;
          import org.springframework.http.HttpHeaders;
          import org.springframework.http.MediaType;
          import org.springframework.test.context.ContextConfiguration;
          import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
          import org.springframework.web.client.RestTemplate;
          
          
          
          @RunWith( SpringJUnit4ClassRunner.class )
          @ContextConfiguration( "classpath:META-INF/conf/test-conf.xml" )
          public class RestWebServiceTest {
          
              @Autowired
              private RestTemplate restTemplate;
          	
          	
              @Test
              public void shouldSaveJsonStringUser() {
          
                  String jsonStringUser = "{"
          		      + "\"id\":\"\"" + ","
          		      + "\"firstName\":\"nicolas\"" + ","
          		      + "\"lastName\":\"loriente\""
          		      + "}";
          
                  HttpHeaders headers = new HttpHeaders();
                  headers.setContentType( MediaType.APPLICATION_JSON );
          
                  HttpEntity request= new HttpEntity( jsonStringUser, headers );
          		
                  User returnedUser = restTemplate.postForObject( "http://localhost:8080/Rest/user/save", request, User.class );
          		
                  // user id is populated when saved to DB
                  assertNotNull( returnedUser.getId() );
                  assertEquals( "nicolas", returnedUser.getFirstName() );
                  assertEquals( "loriente", returnedUser.getLastName() );
          
              }
          	
              @Test
              public void shouldSaveObjectUser() {
          
                  User user = new User();
                  user.setFirstName( "nicolas" );
                  user.setLastName( "loriente" );
          
                  User returnedUser = restTemplate.postForObject( "http://localhost:8080/Rest/user/save", user, User.class );
          		
                  // user id is populated when saved to DB
                  assertNotNull( returnedUser.getId() );
                  assertEquals( "nicolas", returnedUser.getFirstName() );
                  assertEquals( "loriente", returnedUser.getLastName() );
          
              }
          	
          }
          test-conf.xml:
          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"
          	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
          	
          	<!-- Rest Template -->
          	<bean id="restTemplate" class="org.springframework.web.client.RestTemplate" />
          		
          	<!-- Register JSON Converter for RESTful Web Service -->
          	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
              	    <property name="messageConverters">
                  	        <list>
                  	            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
                 	        </list>
             	    </property>
          	</bean>
          	
          </beans>

          Comment

          Working...
          X