I am trying to send some key-value pairs in Android Spring POST Request.It works correctly , if I am using a
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
for that. Is there any way to avoid MultiValueMap & directly send the Class Object as Request.
One solution found is using Reflection , like the following
for (Field field:objAuth.getClass().getDeclaredFields()){
field.setAccessible(true);
map.add(field.getName(),field.get(objAuth)+"");
}
Code Snippet
RestTemplate restTemplate = new RestTemplate(true);
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
Authenticate objAuth = new Authenticate();
objAuth.setUserId("1");
objAuth.setType("Type");
objAuth.setoAuthToken("00112233");
objAuth.setResponseCode("9689");
objAuth.setResponseMessage("Last Message");
/**
* Using Reflection
*/
for (Field field:objAuth.getClass().getDeclaredFields()){
field.setAccessible(true);
map.add(field.getName(),field.get(objAuth)+"");
}
HttpEntity<?> requestEntity = new HttpEntity<Object>(map , requestHeaders);
String response = restTemplate.postForObject("http://posttestserver.com/post.php",requestEntity, String.class);
When posting a media type of
APPLICATION_FORM_URLENCODED
withFormHttpMessageConverter
, you must use aMultiValueMap
, as seen here. Alternatively, if you want to post JSON, Jackson is used internally to convert any object class to JSON output. Spring uses message converters to determine how to read/write objects, and which types are compatible with which media types.