欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring的RestTemplata使用的具体方法

程序员文章站 2023-12-04 17:00:52
基本概念 spring resttemplate 是 spring 提供的用于访问 rest 服务的客户端,resttemplate 提供了多种便捷访问远程http服务的...

基本概念

spring resttemplate 是 spring 提供的用于访问 rest 服务的客户端,resttemplate 提供了多种便捷访问远程http服务的方法,能够大大提高客户端的编写效率,所以很多客户端比如 android或者第三方服务商都是使用 resttemplate 请求 restful 服务。

spring-web的resttemplata是对java底层http的封装,使用resttemplata用户可以不再关注底层的连接建立,并且resttemplata不仅支持rest规范,还可以定义返回值对象类型。

在使用中可以直接new一个resttemplate对象,在我们创建的resttemplate对象中会有一些返回消息的消息转换器,可以根据返回数据的 mediatype 寻找对应的转换器并进行 mediatype 转换。自己也可以创建消息转换器,创建一个类继承abstractgenerichttpmessageconverter<t>类或者实现httpmessageconverter<t>接口,需要注意的是canread方法和canwrite方法最好自己做判断,在writeinternal或write方法中将参数写入到流,在readinternal或read方法中将返回结果从流的body中获取并进行类型映射。

resttemplate对象在底层通过使用java.net包下的实现创建http 请求,可以通过使用clienthttprequestfactory指定不同的http请求方式。

clienthttprequestfactory接口主要提供了两种实现方式:

  1. 一种是simpleclienthttprequestfactory,使用j2se提供的方式(既java.net包提供的方式)创建底层的http请求连接。
  2. 一种方式是使用httpcomponentsclienthttprequestfactory方式,底层使用httpclient访问远程的http服务,使用httpclient可以配置连接池和证书等信息。

resttemplate默认是使用simpleclienthttprequestfactory,内部是调用jdk的httpconnection,默认超时为-1,我们可以自己定义超时时间

simpleclienthttprequestfactory factory = new simpleclienthttprequestfactory();
//设置连接超时,单位毫秒
factory.setconnecttimeout(5000);
//设置读取超时,单位毫秒
factory.setreadtimeout(10000);
resttemplate resttemplate = new resttemplate(factory);

使用get请求:

string url = "http://localhost:80/mandy/login.json?account=123456&password=123456";
result res = resttemplate.getforobject(url, result.class);

resttemplate源码:

  @override
 public <t> t getforobject(string url, class<t> responsetype, object... urlvariables) throws restclientexception {
  requestcallback requestcallback = acceptheaderrequestcallback(responsetype);
  httpmessageconverterextractor<t> responseextractor =
    new httpmessageconverterextractor<t>(responsetype, getmessageconverters(), logger);
  return execute(url, httpmethod.get, requestcallback, responseextractor, urlvariables);
 }

使用get请求直接将参数拼接到地址上最好,不知道什么原因如果使用第三个参数,即便是multivaluemap类型也不行(网上有人说用multivaluemap类型可以,我试了不行)

使用post请求:

hashmap<string, object> map = new hashmap<string, object>();
 map.put("name", "测试");
 map.put("account", "qwer");
 map.put("password", "qwer");
 objectmapper mapper = new objectmapper();
 string jsonstr = null;
 try {
   jsonstr = mapper.writevalueasstring(map);
 } catch (exception e) {
   e.printstacktrace();
 }
//创建http头部实体,填充头部信息,比如数据格式
 httpheaders httpheaders = new httpheaders();
 httpheaders.setcontenttype(mediatype.application_json_utf8);
//创建http实体,可以直接利用构造方法将请求体和请求头放进去
 httpentity<string> httpentity = new httpentity<string>(jsonstr2, httpheaders);
string url = "http://localhost:80/mandy/user_enable.json";
//调用方法进行请求
 result res2 = resttemplate.postforobject(url, httpentity, result.class);

resttemplate源码:

  @override
 public <t> t postforobject(string url, object request, class<t> responsetype, object... urivariables)
   throws restclientexception {

  requestcallback requestcallback = httpentitycallback(request, responsetype);
  httpmessageconverterextractor<t> responseextractor =
    new httpmessageconverterextractor<t>(responsetype, getmessageconverters(), logger);
  return execute(url, httpmethod.post, requestcallback, responseextractor, urivariables);
 }

使用put请求:

hashmap<string, object> map = new hashmap<string, object>();
map.put("user_id", "1");
map.put("enable", 0);
objectmapper mapper = new objectmapper();
string jsonstr = null;
try {
 jsonstr = mapper.writevalueasstring(map);
} catch (jsonprocessingexception e) {
 e.printstacktrace();
}
//创建http头部实体,填充头部信息,比如数据格式
httpheaders httpheaders = new httpheaders();
httpheaders.setcontenttype(mediatype.application_json_utf8);
//创建http实体,可以直接利用构造方法将请求体和请求头放进去
httpentity<string> httpentity = new httpentity<string>(jsonstr, httpheaders);  
string url = "http://localhost:80/mandy/user_enable.json";
resttemplate.put(url , httpentity);

resttemplate源码:

  @override
 public void put(string url, object request, object... urlvariables) throws restclientexception {
  requestcallback requestcallback = httpentitycallback(request);
  execute(url, httpmethod.put, requestcallback, null, urlvariables);
 }

这个方法有个小的缺点就是没有请求结果的返回值,如果需要用到返回值,就不能用这个方法。

如果要使用delete类型的请求,resttemplate的put方法的参数列中只有下面几种

@override
public void delete(string url, object... urlvariables) throws restclientexception {
  execute(url, httpmethod.delete, null, null, urlvariables);
}

@override
public void delete(string url, map<string, ?> urlvariables) throws restclientexception {
  execute(url, httpmethod.delete, null, null, urlvariables);
}

@override
public void delete(uri url) throws restclientexception {
  execute(url, httpmethod.delete, null, null);
}

这些方法并没有给我们参数让我们放请求体内容,所以如果要直接使用resttemplate提供的delete方法,接口必须使用restful风格,将参数放在地址中,通过@pathvariable(value="")注解将参数获取到。

重点: 其实我们可以直接使用resttemplate的 exchange 方法,如下

@override
public <t> responseentity<t> exchange(string url, httpmethod method,
  httpentity<?> requestentity, class<t> responsetype, object... urivariables) throws restclientexception {

  requestcallback requestcallback = httpentitycallback(requestentity, responsetype);
  responseextractor<responseentity<t>> responseextractor = responseentityextractor(responsetype);
  return execute(url, method, requestcallback, responseextractor, urivariables);
}

这里只列举了一个方法,其他的可以看源码,这个方法可以进行所有类型的请求。

在这个方法中,method参数可以通过httpmethod枚举来进行获取,requestentity参数是自己封装的httpentity实体,包含请求体和请求头,responsetype参数是返回结果的映射类,urivariables这个参数给我的印象就是鸡肋(个人看法),获取请求返回接口可以通过方法返回值的getbody()方法获取。

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