rufy rufy - 1 month ago 28
reST (reStructuredText) Question

SPRING: Unable to pass parameters in a post request using rest template

I am using Spring's Rest Template to post a request with data to a web service.
Here is my client code snippet-

RestTemplate restTemplate = new RestTemplate();

MultiValueMap<String, RequestDefinition> map = new LinkedMultiValueMap<String, RequestDefinition>();
map.add("requestJSON", someDataObject);

MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
restTemplate.getMessageConverters().add(jsonHttpMessageConverter);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

restTemplate.postForObject(someUrl, map, String.class);


Here is my servet code post method-

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String reqJSONStr = (String) request.getParameter("requestJSON");

// reqJSONStr is coming as null. No idea why
// some other logic follows here
}


The problem is, in my servlet post method, the requestJSON object is coming as null.
Can somebody please point out the mistake I am doing here.

Answer

Copying from my comment:

I'd guess your data is on the request body in json format, somewhere inside request.getReader()...

As how to pass it as parameter, if your object is complex (has another objects inside as fields) I don't think you can pass all of it as url parameters. If not, try something like this if you HAVE TO send your object as url parameters. You'd also need to read your object in your servlet piece by piece.

RestTemplate rt = new RestTemplate();

rt.setMessageConverters(
        Arrays.asList(new HttpMessageConverter[]{new FormHttpMessageConverter(), new StringHttpMessageConverter()}));

MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("some", someDataObject.getSomeProperty().toString());
map.add("another", someDataObject.getAnotherProperty().toString());

String resp = rt.postForObject("http://scooterlabs.com/echo", map, String.class);

System.out.println(resp);

As you can see, there isn't a HttpMessageConverter that can convert an object to url encoded parameters, so when you put MappingJackson2HttpMessageConverter into list of converters, and try to add an object to request, it will be converted to JSON and end up in the request BODY.

Personally I'd change my servlet code to something that can read JSON from body. JSON is a better choice if you are trying to send a complex object with lots of properties than url encoded form.

Comments