RestTemplate | 使用详解
Posted 结构化思维wz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RestTemplate | 使用详解相关的知识,希望对你有一定的参考价值。
在学习与工作中,常常遇见需要调用他人写好的
API
接口的情况,前端一般采用Ajax
或Axios
来调用后端的接口获取数据,而后端调用接口的方式有很多,这里介绍基于Spring框架的RestTemplate
。
常见的HTTP客户端请求工具:
JDK HttpURLConnection
http client
OkHttp
Spring 家族 RestTemplate
RestTemplate
是一个同步的 Rest API 客户端。下面我们就来介绍下RestTemplate
的常用功能。
RestTemplate的使用
RestTemplate
支持所有 Restful
风格方法,你可以根据需要进行选择,这里我们只介绍一些常用的方法。所有方法都支持URI
模板和URI
参数,支持下面这种写法:
类似 spring mvc 中的 @PathVariable
https://api.apiopen.top/method
restTemplate提供了如下API:
上面的方法我们大致可以分为三组:
getForObject --- optionsForAllow
分为一组,这类方法是常规的 Rest API(GET、POST、DELETE 等)方法调用;exchange
:接收一个RequestEntity
参数,可以自己设置 HTTP method,URL,headers 和 body,返回ResponseEntity
;execute
:通过callback
接口,可以对请求和返回做更加全面的自定义控制。
一般情况下,我们使用第一组和第二组方法就够了。
getForObject的使用
restTemplate.getForObject(要访问的URL, 用于接受结果的类型.class, 入参)
入参可以使用Map的形式,也可以以可变参数的形式,定义:
可变参数:
String result = template.getForObject( "url/count/page", String.class, "5", "1"); //restTemplate会对参数进行URI编码
案例:(随机口吐莲花)
/**
* getForObject
*/
public static String getForObject()
String api1 = "https://nmsl.shadiao.app/api.php?level=min&lang=zh_cn"; //随机生成一句口吐莲花
RestTemplate restTemplate = new RestTemplate();
HashMap<String, Object> uriParams = new HashMap<>();//空参
String res = restTemplate.getForObject(api1,String.class,uriParams);
return res;
getForEntity 的使用
此方法有3个重载 方法参数同
getForObject
。
唯一区别是:
- 返回值是
ResponseEntity<T>
类型ResponseEntity<T>
包含了HTTP响应的头信息header
通过header
可以获取到响应的头信息,比如status 状态码,ContentType
响应类型等等
body
则是响应数据通过HttpMessageConverte
r转换的数据.
public static void getForEntity()
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.apiopen.top/getImages?page=page&count=count"; //获取几张小姐姐的照片看
HashMap<String,Object> uriParams = new HashMap<>();
uriParams.put("page",1);
uriParams.put("count",2);
ResponseEntity<String> responseEntity = restTemplate
.getForEntity(url,String.class,uriParams);
String body = responseEntity.getBody();
System.out.println(body);
"code": 200,
"message": "成功!",
"result": [
"id": 674,
"time": "2020-02-16 04:00:00",
"img": "https://img.lijinshan.site/images/70def23833844b0fa0e6e74041421e37"
,
"id": 675,
"time": "2020-02-16 04:00:00",
"img": "https://img.lijinshan.site/images/999cf7f9728b45deacc0740de53aaff1"
]
除了获取body,还可以用下面的方式获取响应类型和响应状态码:
//获取响应类型 application/json;charset=UTF-8
MediaType contentType = responseEntity.getHeaders().getContentType();
//获取响应状态码 200 OK
HttpStatus statusCode = responseEntity.getStatusCode();
postForObject 的使用
此方法有3个重载与
getForObject
相比多了一个Object request
参数。其他参数作用和getForObject
相同
Object request可以使用以下值作为参数:
org.springframework.util.MultiValueMap
org.springframework.http.HttpEntity
1 org.springframework.util.MultiValueMap
通过MultiValueMap
携带多个参数
在大多数情况下,您不必为每个部件指定Content-Type。内容类型是根据
HttpMessageConverter
所选内容类型自动确定的,不指定Content-Type以便基于文件扩展名的情况下进行自动选择。
public static void postForObject()
RestTemplate template = new RestTemplate();
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
//字符串值
parts.add("fieldPart", "fieldValue");
//图片文件
parts.add("filePart", new FileSystemResource("...logo.png"));
//json
parts.add("jsonPart", new Person("Jason"));
// 手动指定类型,并添加xml
String xmlValue = "<user><name>hoody</name><sex>male</sex></user>";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
parts.add("xmlPart", new HttpEntity<>(xmlValue, headers));
String result = new RestTemplate().postForObject(
"https://example.com/class/user", //String url
parts, //Object request
String.class, //Class<T> responseType
"1"); //Object... uriVariables
2.org.springframework.http.HttpEntity
/**
* PostForObject
*/
public static void postForObject()
RestTemplate restTemplate = new RestTemplate();
//header类型
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
//JSON String
String param = "\\"type\\":\\"student\\"";
//创建请求参数
HttpEntity<String> entity = new HttpEntity<String>(param, httpHeaders);
//调用
String result = new RestTemplate().postForObject(
"https://example.com/class/user", //String url
entity, //Object request
String.class, //Class<T> responseType
"1"); //Object... uriVariables
System.out.println(result);
postForEntity的使用
此方法有3个重载 方法参数同
postForObject
唯一区别是返回值是ResponseEntity
类型ResponseEntity
包含了HTTP响应的头信息header
RestTemplate template = new RestTemplate();
//JSON String
String param = "\\"type\\":\\"student\\"";
//create request header 创建请求头
HttpHeaders headers = new HttpHeaders()
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8)
//创建请求参数
HttpEntity<String> entity = new HttpEntity<String>(param, headers)
//调用
ResponseEntity<String> result = new RestTemplate().postForObject(
"https://example.com/class/user", //String url
entity, //Object request
String.class, //Class<T> responseType
"1") //Object... uriVariables
//获取返回值
String body = entity.getBody();
//获取响应类型
MediaType contentType = entity.getHeaders().getContentType();
//获取响应状态码
HttpStatus statusCode = entity.getStatusCode();
exchange的使用
该方法是通用的请求方式,支持 GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE,当上面的方式不能满足你可采用该方式定制,该方式提供了更加灵活的 API,比如你可以定制 GET 方法的请求头,放入 Jwt Token
等操作,这是getForObject
无法比拟的。
例子:
使用exchange 发起GET请求
设置请求头header:
设置user-agent
设置接收数据类型为JSON
RestTemplate template = new RestTemplate();
//创建header
HttpHeaders headers = new HttpHeaders();
//设置user-agent
headers.add(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (Khtml, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
//添加接收数据媒体类型,JSON
List<MediaType> acceptableMediaTypes = new ArrayList<>();
acceptableMediaTypes.add(MediaType.APPLICATION_JSON_UTF8)
headers.setAccept(acceptableMediaTypes)
//创建请求体
HttpEntity<HttpHeaders> entity = new HttpEntity<>(headers)
//发出请求
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://example.com/hotels/hotel/bookings/booking",
HttpMethod.GET,
entity,
String.class,
"42","21"
)
//获取返回值
String body = entity.getBody();
//获取响应类型
MediaType contentType = entity.getHeaders().getContentType();
//获取响应状态码
HttpStatus statusCode = entity.getStatusCode();
以上是关于RestTemplate | 使用详解的主要内容,如果未能解决你的问题,请参考以下文章
400错误代码,当使用RestTemplate进行Rest API时。