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

时光毁灭记忆、已成空白 提交于 2020-01-05 04:58:06

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/42220390/spring-android-post-request-url-encoded-params-from-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!