【Java开发Spring优雅编程系列4】RestTemplate使用详解及调用第三方请求案例介绍

76 阅读3分钟
一、概述

在我们开发工作中,无论是内部服务调用,还是调用三方服务,都会发起Http请求,在Java中Http请求方式大致有原生HttpURLConnection、HttpClient、Spring的RestTemplate等,如果使用Spring框架,推荐使用RestTemplate,因为使用很方便,开箱即用。 1、RestTemplate 是由 Spring 提供的一个 HTTP 请求工具,从Spring3.0开始支持; 2、提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率; 3、RestTemplate与HttpClient对比: (1)HttpClient代码复杂,还得考虑资源回收,冗余代码多,不建议直接使用; (2)HttpClient需要进行各种序列化和反序列化; (3)RestTemplate与Spring项目很好的集成,推荐使用;

二、主要方法介绍
发送Get请求

Get方法分为两类:getForEntity()和getForObject(); 1、 getForEntity无参使用

ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://localhost:8080/findAll", List.class);        
HttpHeaders headers = responseEntity.getHeaders();  //响应头信息    
HttpStatus statusCode = responseEntity.getStatusCode(); //响应状态       
int code = statusCode.value();
List<UserEntity> list = responseEntity.getBody();//响应体

2、getForEntity有参使用,需要传参数的情况 如果只传入一个参数,可以在url中定义,然后新加参数,如下代码所示:

ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost:8080/get/{id}", UserEntity.class, id);        
UserEntity userEntity = responseEntity.getBody();

如果需要传入多个参数,可以通过Map进行传参,在url使用{}定义参数的key,如下:

HashMap<String, String> map = new HashMap<>();        
map.put("id",123);
map.put("name","hello");
ResponseEntity<UserEntity> responseEntity = restTemplate.getForEntity("http://localhost:8080/get/{id}/{name}", UserEntity.class, map);

3、类似的还有getForObject无参使用

List<UserEntity> list = restTemplate.getForObject("http://localhost:8080/findAll", List.class);

4、getForObject有参使用,同样如果传参为多个,也可以通过Map类型传参:

UserEntity userEntity = restTemplate.getForObject("http://localhost:8080/get/{id}", UserEntity.class, id);
发送Post请求

post分为三类:postForEntity(),postForLocation()和postForObject();

postForEntity()方法
    方法: public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables);
无路径参数:
    ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8080/save", userEntity, String.class);        
String body = responseEntity.getBody();
有路径参数:
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8080/saveByType/{type}", userEntity, String.class, type);        
String body = responseEntity.getBody();
发送Delete、Put请求

一般不推荐使用,无返回值

exchange方法(推荐使用)

1、通过Class方式接收返回值:

<T> ResponseEntity<T> exchange(String url
	, HttpMethod method
	, @Nullable HttpEntity<?> requestEntity
	, Class<T> responseType
	, Object... uriVariables) throws RestClientException;

参数介绍:

参数说明
url调用的url地址
method枚举值,HTTP方法:GET、POST、PUT、DELETE等
requestEntity发起请求时携带的对象:请求头header 和/或 请求体body
responseType请求响应对象的类型
uriVariables就是针对url中的@PathVariable参数,可变长度参数列表
2、通过ParameterizedTypeReference允许传递泛型
<T> ResponseEntity<T> exchange(String url
	, HttpMethod method
	, @Nullable HttpEntity<?> requestEntity
	, ParameterizedTypeReference<T> responseType
	, Object... uriVariables) throws RestClientException;
excute方法

上面所有方法的最后执行都是调用的该方法执行

拓展:Get与Post请求如何选择?

1、Get请求一般是获取数据(但是也可以提交),Post用于提交数据; 2、Get请求参数放在Url中,安全性较差,对于不同的浏览器和服务器有长度限制; Post请求参数在Body中,相比Get请求安全一些,请求没有长度限制; 3、Get请求可以被浏览器缓存,Post请求不能被缓存; 4、get请求只能进行url编码(appliacation-x-www-form-urlencoded),post请求支持多种(multipart/form-data等); 5、get请求刷新服务器或者回退没有影响,post请求回退时会重新提交数据请求。