RestTemplate入门
本篇主要讲解RestTemplate的基本使用,它是Spring提供的用来访问Rest服务的客户端,RestTmplate提供了很多便捷的方法,可以大大提供开发效率,本篇只涉及基本使用,内部原理后续再展开
1.RestTemplate简述
RestTemplate是Spring提供的用于发送HTTP请求的客户端工具,它遵循Restful原则,RestTemplate默认依赖JDK的Http连接工具HttpUrlConnection,你也可以替换不同的源,比如OkHttp、Apache HttpComponents 等等。。
2.HttpMessageConverter
在说RestTemplate之前,先介绍HttpMessageConverter,RestTemplate默认使用的转化HttpMessageConverter去将Http消息转换成POJO 或者 POJO转化成Http消息。在创建RestTemplate的时候会默认添加一组HttpMessageConveter的实现。
HttpMessageConverter源码:
public interface HttpMessageConverter {
//指示此转换器是否可以读取给定的类。
boolean canRead(Class> clazz, @Nullable MediaType mediaType);
//指示此转换器是否可以写给定的类。
boolean canWrite(Class> clazz, @Nullable MediaType mediaType);
//返回List
List getSupportedMediaTypes();
//读取一个inputMessage
T read(Class extends T> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException;
//往output message写一个Object
void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException;
}
RestTemplate中如何添加HttpMessageConverter的
构造器源码:
static {
ClassLoader classLoader = RestTemplate.class.getClassLoader();
romePresent = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader);
jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", classLoader);
jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
jackson2CborPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
jsonbPresent = ClassUtils.isPresent("javax.json.bind.Jsonb", classLoader);
}
public RestTemplate() {
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(new StringHttpMessageConverter());
this.messageConverters.add(new ResourceHttpMessageConverter(false));
try {
this.messageConverters.add(new SourceHttpMessageConverter<>());
}
catch (Error err) {
// Ignore when no TransformerFactory implementation is available
}
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (romePresent) {
this.messageConverters.add(new AtomFeedHttpMessageConverter());
this.messageConverters.add(new RssChannelHttpMessageConverter());
}
if (jackson2XmlPresent) {
this.messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
}
else if (jaxb2Present) {
this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
if (jackson2Present) {
this.messageConverters.add(new MappingJackson2HttpMessageConverter());
}
else if (gsonPresent) {
this.messageConverters.add(new GsonHttpMessageConverter());
}
else if (jsonbPresent) {
this.messageConverters.add(new JsonbHttpMessageConverter());
}
if (jackson2SmilePresent) {
this.messageConverters.add(new MappingJackson2SmileHttpMessageConverter());
}
if (jackson2CborPresent) {
this.messageConverters.add(new MappingJackson2CborHttpMessageConverter());
}
this.uriTemplateHandler = initUriTemplateHandler();
}
从RestTemplate的构造器源码中我们可以看到构造方法中 根据ClassUtils.isPresent判断当前项目是否存在某些jar包向RestTemplate中添加不同的 HttpMessageConverter实现,Spring默认会添加 StringHttpMessageConverter , MappingJackson2XmlHttpMessageConverter等等
3.getForObject()
首先来看Get请求 RestTemplate提供了2种方法其中一种就是 getForObject()方法
public T getForObject(String url, Class responseType, Object... uriVariables){}
public T getForObject(String url, Class responseType, Map uriVariables)
public T getForObject(URI url, Class responseType)
3.1 不带参数的Get请求
客户端
String url = "http://localhost:9999/testGetMethod";
String str = restTemplate.getForObject(url , String.class);、
服务端
@RequestMapping("/testGetMethod")
public String testGetMethod(){
return "hello";
}
3.2 带参数的Get请求 (按{}顺序绑定参数)
客户端
String url = "http://localhost:9999/testGetMethod/{talk}/{name}";
//或者testGetMethod/{1}/{2} {里面的参数无所谓,只是根据下面的Object... uriVariables 逐一绑定到上面{} 中去的}
String str = restTemplate.getForObject(url , String.class,"hello" , "johnny");
服务端
@RequestMapping("/testGetMethod/{talk}/{name}")
public String testGetMethod(@PathVariable("talk") String talk ,
@PathVariable("name") String name){
log.info("【{} : {}】" , talk , name);
return "hello";
}
说明{} http://localhost:9999/testGetMethod/{talk}/{name} 里面的参数名称无所谓,只是根据下面的Object... uriVariables 逐一绑上去的,具体绑定源码请看 DefaultUriBuilderFactory的fromUriString方法内部是根据正则表达式进行绑定的,最终将返回 URI,URI的string属性 就是绑定后要访问的路径
//不早了 先写这么多吧 明天把下面的补齐 ,先去睡觉了!!!
//继续补齐。。
3.3 带参数的Get请求(按Map的key绑定{}参数)
String url = "http://localhost:9999/testGetMethod/{talk}/{name}";
Map map = new HashMap<>();
map.put("talk" , "hello");
map.put("name" , "johnny");
String str = restTemplate.getForObject(url , String.class,map);
可以看出来是通过Map绑定参数的,这个和上面不一样的是 map的key 一定要和 url中 {} 中的 保持一致 ,如果不一致会报错
String url = "http://localhost:9999/testGetMethod/{talk}/{name}";
map.put("talk2" , "hello");
源码
4.getForEntity()
RestTemplate 提供的Get请求的第二种方法 ,基本和getForObject一致 ,就是返回类型不同,它是在getForObject返回的基础上再包装了一层 ResponseEntity 用于包含Http请求的全部信息
public ResponseEntity getForEntity(String url, Class responseType, Object... uriVariables){}
public ResponseEntity getForEntity(String url, Class responseType, Map uriVariables){}
public ResponseEntity getForEntity(URI url, Class responseType){}
4.1 不带参数的Get请求
String url = "http://localhost:9999/testGetMethodForEntity/";
ResponseEntity responseEntity = restTemplate.getForEntity(url , Student.class);
responseEntity.getStatusCode();
responseEntity.getHeaders();
responseEntity.getBody();
log.info("【responseEntity : {}】" , responseEntity);
4.2 带参数的Get请求 (按{}顺序绑定参数)
String url = "http://localhost:9999/testGetMethodForEntity/{name}/{age}";
ResponseEntity responseEntity = restTemplate.getForEntity(url , Student.class , "johnny" , "23");
log.info("【responseEntity : {}】" , responseEntity);
4.3 带参数的Get请求 (按Ma的keyp绑定{}参数)
String url = "http://localhost:9999/testGetMethodForEntity/{name}/{age}";
Map map = new HashMap<>();
map.put("name","johnny");
map.put("age" , "23");
ResponseEntity responseEntity = restTemplate.getForEntity(url , Student.class ,"map");
log.info("【responseEntity : {}】" , responseEntity);
但是,通常情况下我们并不想要Http请求的全部信息,只需要相应体即可.对于这种情况,RestTemplate提供了 getForObject() 方法用来只获取 响应体信息.
getForObject 和 getForEntity 用法几乎相同,指示返回值返回的是 响应体,省去了我们 再去 getBody() .
5.postForObject()
public T postForObject(String url, @Nullable Object request, Class responseType, Object... uriVariables)
throws RestClientException {}
public T postForObject(String url, @Nullable Object request, Class responseType, Map uriVariables)
throws RestClientException {}
public T postForObject(URI url, @Nullable Object request, Class responseType) throws RestClientException {}
5.1 post请求 提交参数 Student 对象
客户端代码:
String url = "http://localhost:9999/testPostMethodForObject";
Student student = new Student();
student.setName("johnny");
student.setAge("23");
String msg = restTemplate.postForObject(url , student , String.class);
服务端代码:
@RequestMapping("/testPostMethodForObject")
public String testGetMethodForEntity(@RequestBody Student student){
log.info("【studeng: {}】" , student);
return "success";
}
6.postForEntity()
public T postForObject(String url, @Nullable Object request, Class responseType, Object... uriVariables)
throws RestClientException {}
public T postForObject(String url, @Nullable Object request, Class responseType, Map uriVariables)
throws RestClientException {}
public T postForObject(URI url, @Nullable Object request, Class responseType) throws RestClientException {}
6.1 post请求 提交参数 Student 对象
@RequestMapping("/testPostMethodForEntity")
public void testPostMethodForEntity(){
String url = "http://localhost:9999/testPostMethodForEntity";
Student student = new Student();
student.setName("johnny");
student.setAge("23");
ResponseEntity responseEntity = restTemplate.postForEntity(url , student , String.class);
log.info(responseEntity.getBody());
}
7. ResponseExtractor 源码
可以看出来postForEntity和postForObject 几乎一样。
唯有 ResponseExtractor
HttpMessageConverterExtractor.extractData()方法
ResponseEntityResponseExtractor.extractData()方法
总结:
本篇主要讲解RestTemplate的基本的 Get Post 的用法,简单的涉及了一点源码,其实内部源码很多 很深 包括和解析url模板 绑定参数的 UriBuilderFactory UriTemplateHandler 等等 , 建议去跟着跑一遍会更加熟悉 用起来也更加轻松。
个人博客网站 https://www.askajohnny.com 欢迎来访问!
本文由博客一文多发平台 OpenWrite 发布!