Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring RestTemplate to POST params with objects

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?

like image 378
Matt Crysler Avatar asked Sep 30 '22 04:09

Matt Crysler


1 Answers

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!

like image 81
Matt Crysler Avatar answered Nov 14 '22 19:11

Matt Crysler