本文来自:https://www.sojson.com/blog/350.html
以前我们创建一个Http请求,很复杂,要写很多代码,而且请求还有各种兼容问题。而用 RestTemplate
的话优雅的几行代码就可以解决,并且是可以直接返回对象。
RestTemplate 是 Spring 用于同步请求client端的核心类,简化了与 HTTP 的通信,并满足RestFul
原则,RestTemplate
默认依赖 JDK 的HTTP
连接工具。当然你也可以 通过setRequestFactory
属性切换到不同的HTTP
数据源,比如Apache HttpComponents
、Netty
和OkHttp
,都是支持的。
我们先做一个普通的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 restTemplate = new RestTemplate();
WeatherDto dto = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/"+101010100 , WeatherDto.class);
上面其实是一个简单的带参数请求,用“{1}”、“{2}”、“{3}”... 方式传参,如果是地址拼接的方式,可以N个。
上一篇博客采用这个方式,模拟的Http请求,请求天气接口数据:https://www.sojson.com/blog/349.html 。
因为是Get请求,其实就是问号的方式带参数请求
Map<String,String> map = new HashMap();
map.put("id",101010100);
RestTemplate restTemplate = new RestTemplate();
Details detail = restTemplate.getForObject("http://example.sojson.com/detail.html" , Details.class,map);
其实上面的1和2算是简单的请求,就是直接返回了Object
实例对象。而我们要获取详细的详细,如返回status
、Header
信息等。那就得用 getForEntity
。
看看源码里的参数描述,其实是和 getForObject
一致,我这里网络不行没下载下来源码包,凑合看看。
<T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Object... var3) throws RestClientException;
<T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Map<String, ?> var3) throws RestClientException;
<T> ResponseEntity<T> getForEntity(URI var1, Class<T> var2) throws RestClientException;
HTTP 实例讲解:
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<String, String> map= new LinkedMultiValueMap<>();
map.add("id", "101010100");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<WeatherDto> 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
实现的。
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/350.html
转载时必须以链接形式注明原始出处及本声明。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。