Announcement Announcement Module
Collapse
No announcement yet.
RestTemplate and JSON: where is the payload Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • 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:
    Code:
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(new MappingJacksonHttpMessageConverter()); 
    converters.add(new StringHttpMessageConverter());
    converters.add(new FormHttpMessageConverter());
    restTemplate.setMessageConverters(converters);
    After build the template, the call was like:
    Code:
    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:
    Code:
    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?
Working...
X