Using Spring RestTemplate to POST params with objects
-
21-12-2019 - |
Question
I am trying to send a POST request using Spring's RestTemplate functionality but am having an issue sending an object. Here is the code I am using to send the request:
RestTemplate rt = new RestTemplate();
MultiValueMap<String,Object> parameters = new LinkedMultiValueMap<String,Object>();
parameters.add("username", usernameObj);
parameters.add("password", passwordObj);
MyReturnObj ret = rt.postForObject(endpoint, parameters, MyRequestObj.class);
I also have a logging interceptor so I can debug the input parameters and they are almost correct! Currently, the usernameObj
and passwordObj
parameters appear as such:
{"username":[{"testuser"}],"password":[{"testpassword"}]}
What I want them to look like is the following:
username={"testuser"},password={"testpassword"}
Assume that usernameObj
and passwordObj
are Java objects that have been marshalled into JSON.
What am I doing wrong?
Solution
Alright, so I ended up figuring this out, for the most part. I ended up just writing a marshaller/unmarshaller so I could handle it at a much more fine grained level. Here was my solution:
RestTemplate rt = new RestTemplate();
// Create a multimap to hold the named parameters
MultiValueMap<String,String> parameters = new LinkedMultiValueMap<String,String>();
parameters.add("username", marshalRequest(usernameObj));
parameters.add("password", marshalRequest(passwordObj));
// Create the http entity for the request
HttpEntity<MultiValueMap<String,String>> entity =
new HttpEntity<MultiValueMap<String, String>>(parameters, headers);
// Get the response as a string
String response = rt.postForObject(endpoint, entity, String.class);
// Unmarshal the response back to the expected object
MyReturnObj obj = (MyReturnObj) unmarshalResponse(response);
This solution has allowed me to control how the object is marshalled/unmarshalled and simply posts strings instead of allowing Spring to handle the object directly. Its helped immensely!
OTHER TIPS
For Client Side
To pass the object as json string, use MappingJackson2HttpMessageConverter
.
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
For Server Side spring configuration
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>