服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - 如何使用Spring RestTemplate访问restful服务

如何使用Spring RestTemplate访问restful服务

2021-06-08 14:13低调的微胖 Java教程

这篇文章主要介绍了如何使用Spring RestTemplate访问restful服务,详细的介绍了什么是RestTemplate以及简单实现,非常具有实用价值,需要的朋友可以参考下

一. 什么是resttemplate

spring's central class for synchronous client-side http access.
it simplifies communication with http servers, and enforces restful principles.
it handles http connections, leaving application code to provide urls(with possible template variables) and extract results.

 上面这段是resttemplate类中的简单介绍,resttemplate是spring3.0后开始提供的用于访问 rest 服务的轻量级客户端,相较于传统的httpurlconnection、apache httpclient、okhttp等框架,resttemplate大大简化了发起http请求以及处理响应的过程。本文关注resttemplate是如何使用的,暂不涉及内部的实现原理。

二.一个简单的例子。

定义一个简单的restful接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@restcontroller
public class testcontroller
{
  @requestmapping(value = "testpost", method = requestmethod.post)
  public responsebean testpost(@requestbody requestbean requestbean)
  {
    responsebean responsebean = new responsebean();
    responsebean.setretcode("0000");
    responsebean.setretmsg("succ");
 
    return responsebean;
  }
}

使用resttemplate访问该服务

?
1
2
3
4
5
6
7
8
9
10
//请求地址
string url = "http://localhost:8080/testpost";
//入参
requestbean requestbean = new requestbean();
requestbean.settest1("1");
requestbean.settest2("2");
requestbean.settest3("3");
 
resttemplate resttemplate = new resttemplate();
responsebean responsebean = resttemplate.postforobject(url, requestbean, responsebean.class);

从这个例子可以看出,使用resttemplate访问restful接口非常的简单粗暴无脑。(url, requestmap, responsebean.class)这三个参数分别代表 请求地址、请求参数、http响应转换被转换成的对象类型。

resttemplate方法的名称遵循命名约定,第一部分指出正在调用什么http方法,第二部分指示返回的内容。本例中调用了resttemplate.postforobject方法,post指调用了http的post方法,object指将http响应转换为您选择的对象类型。还有其他很多类似的方法,有兴趣的同学可以参考官方api

三.手动指定转换器(httpmessageconverter)

我们知道,调用reseful接口传递的数据内容是json格式的字符串,返回的响应也是json格式的字符串。然而resttemplate.postforobject方法的请求参数requestbean和返回参数responsebean却都是java类。是resttemplate通过httpmessageconverter自动帮我们做了转换的操作。

默认情况下resttemplate自动帮我们注册了一组httpmessageconverter用来处理一些不同的contenttype的请求。
如stringhttpmessageconverter来处理text/plain;mappingjackson2httpmessageconverter来处理application/json;mappingjackson2xmlhttpmessageconverter来处理application/xml。
你可以在org.springframework.http.converter包下找到所有spring帮我们实现好的转换器。
如果现有的转换器不能满足你的需求,你还可以实现org.springframework.http.converter.httpmessageconverter接口自己写一个。详情参考官方api

选好了httpmessageconverter后怎么把它注册到我们的resttemplate中呢。

?
1
2
3
4
5
6
7
resttemplate resttemplate = new resttemplate();
//获取resttemplate默认配置好的所有转换器
list<httpmessageconverter<?>> messageconverters = resttemplate.getmessageconverters();
//默认的mappingjackson2httpmessageconverter在第7个 先把它移除掉
messageconverters.remove(6);
//添加上gson的转换器
messageconverters.add(6, new gsonhttpmessageconverter());

这个简单的例子展示了如何使用gsonhttpmessageconverter替换掉默认用来处理application/json的mappingjackson2httpmessageconverter。

四.设置底层连接方式

要创建一个resttemplate的实例,您可以像上述例子中简单地调用默认的无参数构造函数。这将使用java.net包中的标准java类作为底层实现来创建http请求。

但很多时候我们需要像传统的httpclient那样设置http请求的一些属性。resttemplate使用了一种很偷懒的方式实现了这个需求,那就是直接使用一个httpclient作为底层实现......

?
1
2
3
4
5
6
7
8
//生成一个设置了连接超时时间、请求超时时间、异常最大重试次数的httpclient
requestconfig config = requestconfig.custom().setconnectionrequesttimeout(10000).setconnecttimeout(10000).setsockettimeout(30000).build();
httpclientbuilder builder = httpclientbuilder.create().setdefaultrequestconfig(config).setretryhandler(new defaulthttprequestretryhandler(5, false));
httpclient httpclient = builder.build();
//使用httpclient创建一个clienthttprequestfactory的实现
clienthttprequestfactory requestfactory = new httpcomponentsclienthttprequestfactory(httpclient);
 //clienthttprequestfactory作为参数构造一个使用作为底层的resttemplate
resttemplate resttemplate = new resttemplate(requestfactory);

五.设置拦截器(clienthttprequestinterceptor)

有时候我们需要对请求做一些通用的拦截设置,这就可以使用拦截器进行处理。拦截器需要我们实现org.springframework.http.client.clienthttprequestinterceptor接口自己写。

举个简单的例子,写一个在header中根据请求内容和地址添加令牌的拦截器。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class tokeninterceptor implements clienthttprequestinterceptor
{
  @override
  public clienthttpresponse intercept(httprequest request, byte[] body, clienthttprequestexecution execution) throws ioexception
  {
    //请求地址
    string checktokenurl = request.geturi().getpath();
    //token有效时间
    int tttime = (int) (system.currenttimemillis() / 1000 + 1800);
    //请求方法名 post、get等
    string methodname = request.getmethod().name();
    //请求内容
    string requestbody = new string(body);
    //生成令牌 此处调用一个自己写的方法,有兴趣的朋友可以自行google如何使用ak/sk生成token,此方法跟本教程无关,就不贴出来了
    string token = tokenhelper.generatetoken(checktokenurl, tttime, methodname, requestbody);
    //将令牌放入请求header中
    request.getheaders().add("x-auth-token",token);
 
    return execution.execute(request, body);
  }
}

创建resttemplate实例的时候可以这样向其中添加拦截器

?
1
2
3
resttemplate resttemplate = new resttemplate();
    //向resttemplate中添加自定义的拦截器
    resttemplate.getinterceptors().add(new tokeninterceptor());

六.总结

通过本章的讲解,想必读者初步的了解了如何使用resttemplate方便快捷的访问restful接口。其实resttemplate的功能非常强大,作者也仅仅学了点皮毛。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/c9644755dd5e

延伸 · 阅读

精彩推荐