OAuth2RestTemplate post请求 getForEntity方法 json格式数据 遇到的多个坑

1. java对象转json;

JSONObject jsonObject=JSONObject.fromObject(userDto);

pom.xml配置

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

2. 解决乱码问题,只需要在调用的地方前面加一句;

oAuth2RestTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));

3. OAuth2RestTemplate 继承自RestTemplate,其实用法和参数也都差不多,用postForEntity发送post请求;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), headers);
        oAuth2RestTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        ResponseEntity<String> responseEntity = oAuth2RestTemplate.postForEntity(authRequestUrl.concat("/resource/user/add/user"),request,String.class);

如有415错误,一般是因为ContentType没有设置或者设置错误的问题。

5. 接收到的json字符串转回java对象,这里的UserDto对象中存在两个List,所以要放入Map中才能转换成功;

        Map dtoMap=new HashMap();
        dtoMap.put("roleDto",RoleDto.class);
        dtoMap.put("orgDto",OrgDto.class);
        UserDto userDto1=(UserDto)JSONObject.toBean(JSONObject.fromObject(userDtoJsonStrng),UserDto.class,dtoMap);

版权声明:本文为Pluto_sang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。