自定义HttpMessageConverter实现RestTemplate的exchange方法返回自定义格式数据
一 概述 实现如下效果代码,且可正常获取到返回数据: ResponseEntity<JsonObject> resEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JsonObject.class,uriVariables); restTemplate的get和POST请求都有类型参数设置,所以可以直接返回转换成自定义的格式.比如: restTemplate.getForObject("http://www.baiud.com",JsonObject.class); 但是exchange是无法指定返回类型的,只能使用spring默认提供的几种转换器转换的格式,定义其他格式会报错或者返回实体body为空 restTemplate的post方法支持设置header,但是get方法不支持,假如现在有个需求,使用get方法需要设置header权限,且返回我想要的格式,那么自定义HttpMessageConverter就派上用场了 也提现了spring非常强大的可扩展性 二 步骤 新建自定义转换类: /** * 接口请求返回数据格式转换处理类,只处理String->JsonObject */ public class StringToJsonObjectMessageConverter extends