简体   繁体   中英

Spring Android - POST Request - URL Encoded Params from Class Object

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 with FormHttpMessageConverter , you must use a MultiValueMap , 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM