RestTemplate简介
RestTemplate是由Spring框架提供的一个可用于应用中调用rest服务的类它简化了与http服务的通信方式,统一了RESTFul的标准,封装了http连接,我们只需要传入url及其返回值类型即可。
相较于之前常用的HttpClient,RestTemplate是一种更为优雅的调用RESTFul服务的方式。
在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计原则与许多其他Spring的模板类(例如JdbcTemplate)相同,为执行复杂任务提供了一种具有默认行为的简化方法。
RestTemplate默认依赖JDK提供了http连接的能(HttpURLConnection),
如果有需要的话也可以通过setRequestFactory方法替换为
例如Apache、 HttpCompoent、Netty或OKHttp等其他Httplibaray。
考虑到了RestTemplate类是为了调用REST服务而设计的,
因此它的主要方法与REST的基础紧密相连就不足为奇了,
后者时HTTP协议的方法:HEAD、GET、POST、PUT、DELETE、OPTIONS
例如: RestTemplate类具有headForHeaders()、getForObject()、putForObject(),put()和delete()等方法。
创建RestTemplate
因为RestTemplate是Spirng框架提供的所以只要是一个Springboot项目就不用考虑导包的问题,这些都是提供好的。
但是Spring并没有将其加入SpringBean容器中,需要我们手动加入,
因为我们首先创建一个Springboot配置类,再在配置类中将我们的RestTemlate注册到Bean容器中。
/**
* resttemplate自定义配置引入连接池
* @return restTemplate
*/
@Bean
public RestTemplate restTemplate(){
OkHttp3ClientHttpRequestFactory okhttp3 = new OkHttp3ClientHttpRequestFactory();
//设置连接超时时间
okhttp3.setConnectTimeout(15000);
//设置读取超时时间
okhttp3.setReadTimeout(15000);
okhttp3.setWriteTimeout(15000);
RestTemplate restTemplate = new RestTemplate(okhttp3);
// 解决中文乱码
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
messageConverters.add(new TextHtmlJackson2HttpMessageConverter());
// 自定义错误响应,返回详细的错误信息
restTemplate.setErrorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return true;
}
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
}
});
return restTemplate;
}
RestTemplate API使用
在使用RestTemplate前先让我们看看RestTemplate有哪些API
GET请求
通过上图我们可以发现RestTemlate发送GET请求的方法有两种
public T getForObject(…)
public ResponseEntity getForEntity(…)
getForEntity()
后缀带有Entity的方法都代表返回一个ResponseEntity,
ResponseEntity是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码,contentType、contentLength、响应消息体等
通过它继承父类(HttpEntity)的getHeader()方法我们可以获取contentType、contentLength、响应消息体等。比如下面这个例子。
public void queryWeather() {
ResponseEntity<Object> forEntity = restTemplate.getForEntity("https://restapi.amap.com/v3/weather/weatherInfo?city=510100&key=e7a5fa943f706602033b6b329c49fbc6", Object.class);
System.out.println("状态码:"+forEntity.getStatusCode());
System.out.println("状态码内容:"+forEntity.getStatusCodeValue());
HttpHeaders headers = forEntity.getHeaders();
System.out.println("响应头:"+headers);
Object body = forEntity.getBody();
System.out.println("响应内容:"+body);
}
该例子中getForEntity()方法
第一个参数为我要调用服务的URL,
第二个参数则为响应内容的类的类型(Java嘛万物皆对象
第三个参数为一个可变参数代表着调用服务时的传参(可以使用key-value的map来传入参数)
get请求也可通过向在url上添加查询参数来发送带有请求的参数
getForObject()
相比于前者getForEntity()该方法则是,更偏向于直接获取响应内容的,
因为他直接返回响应实体的body(响应内容)。比如下面这个例子
public void queryWeather() {
Object body = restTemplate.getForObject("https://restapi.amap.com/v3/weather/weatherInfo?city=510100&key=e7a5fa943f706602033b6b329c49fbc6", Object.class);
System.out.println(body);
}
POST请求
public URI postForLocation(…)
public T postForObject(…)
public ResponseEntity postForEntity(…)
后两种用法与GET基本一致不做详细介绍,这里着重介绍postForLocation()
postForEntity()
必须用ResponseEntity对象接
该方法有三个参数, 第一个为调用服务的地址(URL) 第二个参数表示上传的参数(json格式提交)
第三个表示返回响应内容的具体类型 第四个参数也用于指定参数(在URL中添加)
/**
* 发送post json请求
* @param paramMap 请求参数
* @param url URL
* @return 响应json中的data信息
*/
public static JSONObject postJsonRequest(Map<String, Object> paramMap, String url) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Access-Token", redisUtils.get(RedisKeys.ACCESS_TOKEN));
HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramMap, headers);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
JSONObject respJson = responseEntity.getBody();
if (Integer.valueOf(0).equals(respJson.get("code"))) {
return (JSONObject) JSON.toJSON(respJson.get("data"));
} else {
log.info("接口 {} 请求失败 {}", url, respJson);
throw new QnmManageException("接口请求失败 " + respJson);
}
} else {
throw new QnmManageException("接口请求错误");
}
}
postForObject()
使用方法与getForObject类似只是多了一个传入对象参数(传入方式与postForEntity()相同)
postForLocation()
postForLocation传参用法与前两者一致,只不过返回从实体变成了一个URL,
因此它不需要指定返回响应内容的类型。
public void queryWeather() {
User user = new User();
user.setName("鲁大师");
URI uri = restTemplate.postForLocation("https://httpbin.org/post", user);
System.out.println(uri);
}
EXCHANGE方法
ResponseEntity exchange()
该接口与其他接口不同 该方法允许用户指定请求的方法(get,post,put等)
可以在请求中增加body以及头信息,其内容通过参数HttpEntity<?> requestEntity描述
exchange支持’含参数的类型(即泛型)'作为返回类型
ParameterizedTypeReferenceresponseType 描述该方法支持五个参数 第一个是服务地址 第二个是请求方法
第三个是写入的请求实体 第四个是响应内容的类型 第五个是扩展模板的变量或包含URI模板变量的映射
@Test
void contextLoads() {
//请求地址
String url = "http://httpbin.org/post";
User user = new User();
user.setName("彭于晏");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> userHttpEntity = new HttpEntity<>(user, httpHeaders);
ResponseEntity<Object> exchange = restTemplate.exchange(url, HttpMethod.POST, userHttpEntity, Object.class);
System.out.println(exchange);
}
上述代码模拟了一个简单的POST请求 可以理解为可以动态的指定请求方法和请求实体的一个方法。
响应实体
/**
* 发送get请求
* @param paramMap 请求参数
* @param url URL
* @return 响应json中的data信息
*/
public static JSONObject getRequest(Map<String, Object> paramMap, String url) {
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Token", redisUtils.get(RedisKeys.ACCESS_TOKEN));
HttpEntity<Map<String, Object>> request = new HttpEntity<>(null, headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
for (Map.Entry<String, Object> param : paramMap.entrySet()) {
String key = param.getKey();
String val = param.getValue() instanceof String ? (String) param.getValue() : JSON.toJSONString(param.getValue());
builder.queryParam(key, val);
}
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, request, JSONObject.class);
if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
JSONObject respJson = responseEntity.getBody();
if (Integer.valueOf(0).equals(respJson.get("code"))) {
return (JSONObject) JSON.toJSON(respJson.get("data"));
} else {
log.info("接口 {} 请求失败 {}", url, respJson);
throw new QnmManageException("接口请求失败 " + respJson);
}
} else {
throw new QnmManageException("接口请求错误");
}
}