以前我们创建一个Http请求,很复杂,要写很多代码,而且请求还有各种兼容问题。而用 RestTemplate 的话优雅的几行代码就可以解决,并且是可以直接返回对象。

RestTemplate 是  Spring  用于同步请求client端的核心类,简化了与  HTTP   的通信,并满足RestFul原则,RestTemplate默认依赖  JDK  的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP数据源,比如Apache HttpComponents、Netty和OkHttp,都是支持的。

HTTP Get 请求

我们先做一个普通的Http请求,直接上源码。try {

HttpClient client = new HttpClient();

//创建一个Get请求

GetMethod method = new GetMethod("http://t.weather.sojson.com/api/weather/city/"+101010100);

client.executeMethod(method);

//获取String类型的返回值

String res = method.getResponseBodyAsString();

//使用gson转换为对象

WeatherDto dto = new Gson().fromJson(res,WeatherDto.class);

} catch (IOException e) {

e.printStackTrace();

}

这是一个最简单的Http请求,把返回值使用   Gson   来转换成对象。

使用RestTemplate HTTP Get 请求RestTemplate restTemplate = new RestTemplate();

WeatherDto dto = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/"+101010100 , WeatherDto.class);

2行代码就完成了,并且将结果转换为对象。

1.RestTemplate URL拼接参数请求RestTemplate restTemplate = new RestTemplate();

WeatherDto dto = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/{1}" , WeatherDto.class,101010100);

上面其实是一个简单的带参数请求,用“{1}”、“{2}”、“{3}”... 方式传参,如果是地址拼接的方式,可以N个。

2.RestTemplate 多个参数请求

因为是Get请求,其实就是问号的方式带参数请求Map map = new HashMap();

map.put("id",101010100);

RestTemplate restTemplate = new RestTemplate();

Details detail = restTemplate.getForObject("http://example.sojson.com/detail.html" , Details.class,map);

3.RestTemplate getForEntity 请求

其实上面的1和2算是简单的请求,就是直接返回了Object 实例对象。而我们要获取详细的详细,如返回status、Header信息等。那就得用 getForEntity 。

看看源码里的参数描述,其实是和 getForObject 一致,我这里网络不行没下载下来源码包,凑合看看。 ResponseEntity getForEntity(String var1, Class var2, Object... var3) throws RestClientException;

ResponseEntity getForEntity(String var1, Class var2, Map var3) throws RestClientException;

ResponseEntity getForEntity(URI var1, Class var2) throws RestClientException;

实例讲解:RestTemplate restTemplate = new RestTemplate();

String url = "http://example.sojson.com/detail.html";

//添加请求头

HttpHeaders headers = new HttpHeaders();

//form表单提交 application/x-www-form-urlencoded

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

//组装参数

MultiValueMap map= new LinkedMultiValueMap<>();

map.add("id", "101010100");

HttpEntity> request = new HttpEntity<>(map, headers);

ResponseEntity response = restTemplate.postForEntity( url, request , WeatherDto.class );

//返回对象

WeatherDto dto = response.getBody();

//HTTP状态

int status = response.getStatusCodeValue();

//Spring 封装的

HttpStatus statusCode = response.getStatusCode();

//封装的对应状态请求,返回来都是 Boolean 类型

statusCode.is2xxSuccessful();//2开头的成功状态

statusCode.is3xxRedirection();//3开头重定向

statusCode.is4xxClientError();//4开头客户端错误

statusCode.is5xxServerError();//5开头服务端异常

具体可以自行测试下。

我们看源码知道还有 Post请求 方法。restTemplate.postForEntity( ... )

restTemplate.postForObject(... )

方法传参是和上面讲解的 Get请求 的使用方式一模一样。

有兴趣的可以测试下我们的在线 HTTP模拟请求 工具 ,就是采用 restTemplate 实现的。