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:
After build the template, the call was like: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);
It failed due to "no parameter in the request". It seems that the httpRequest body was empty.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);
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:
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.*Code:String jsonString = "{.... build the params in JSON format.....}"; String s = restTemplate.postForObject(my_url, jsonString, String.class);
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?


Reply With Quote