Announcement Announcement Module
No announcement yet.
RestTemplate and JSON: where is the payload Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • RestTemplate and JSON: where is the payload

    I need to connect to a 3rd party REST service. The services support POST/JSON to their endpoint, and insist that the arguments of each service must be placed in the body of the http request, not in the url query string.

    Here's the codes using restTemplate:
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new MappingJacksonHttpMessageConverter()); 
    converters.add(new StringHttpMessageConverter());
    converters.add(new FormHttpMessageConverter());
    After build the template, the call was like:
    MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    body.add("username", "password");
    body.add("password", "username");
    MyClass returnValue = restTemplate.postForObject(my_url, body, MyClass .class);
    It failed due to "no parameter in the request". It seems that the httpRequest body was empty.

    Then I tried another way as "control":
    It's almost the same way to build restTemplate, but removed the MappingJacksonHttpMessageConverter from the template's converter list, that is, the payload won't be automatically convert to JSON style. The invocation was:
    String jsonString = "{.... build the params in JSON format.....}";
    String s = restTemplate.postForObject(my_url, jsonString, String.class);
    It worked. It seems to me that MappingJacksonHttpMessageConverter magically put the arguments out of the http request body. BTW, the JSON parser library was org.codehaus.jackson.*

    I do want to use the convenient JSON converter, so that I don't have to do it by myself. any idea to solve it?