spring学习之restTemplate常用方法介绍

什么是RestTemplate

  • RestTemplate用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果
  • 默认情况下,RestTemplate默认使用jdk提供http链接的能力(HttpURLConnection)
  • 可以通过setRequestFactory属性切换到不同的HTTP源,Apache HttpComponents,Netty和OkHttp。

常用方法

restTemplate其他的先不讲,直接上来操作,熟个手

getForObject

getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject

  1. public T getForObject(String url, Class responseType, Object… uriVariables)
    String oneGet = restTemplate.getForObject("http://localhost:6788/oneGet", String.class);
    System.out.println(oneGet);
    //可以用一个数字做占位符,最后是一个可变长度的参数,来一一替换前面的占位符
    String oneGet1 = restTemplate.getForObject("http://localhost:6788/oneGet/{1}", String.class,"1");
    System.out.println(oneGet1);
    
  2. public T getForObject(String url, Class responseType, Map<String, ?> uriVariables)
    //也可以前面使用id={id}这种形式,最后一个参数是一个map,map的key即为前边占位符的名字,map的value为参数值
    HashMap<String, Object> twoGetMap = new HashMap<>();
    twoGetMap.put("id","1");
    String twoGet = restTemplate.getForObject("http://localhost:6788/twoGet?id={id}", String.class,twoGetMap);
    System.out.println(twoGet);
    
  3. public T getForObject(URI url, Class responseType)
    String threeGet = restTemplate.getForObject(new URI("http://localhost:6788/threeGet"), String.class);
    System.out.println(threeGet);
    
    ====================getForObject=======================
    {"code":1,"message":"","data":"oneGet"}
    {"code":1,"message":"","data":"oneGet1--1"}
    {"code":1,"message":"","data":"twoGet--1"}
    {"code":1,"message":"","data":"threeGet"}
    

getForEntity

getForEntity方法的返回值是一个ResponseEntity,ResponseEntity是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等

  1. public ResponseEntity getForEntity(String url, Class responseType, Object… uriVariables)
    ResponseEntity<String> oneGetEntity = restTemplate.getForEntity("http://localhost:6788/oneGet", String.class);
    System.out.println(oneGetEntity);
    ResponseEntity<String> oneGetEntity1 = restTemplate.getForEntity("http://localhost:6788/oneGet/{1}", String.class, "1");
    System.out.println(oneGetEntity1);
    
  2. public ResponseEntity getForEntity(String url, Class responseType, Map<String, ?> uriVariables)
    //也可以前面使用id={id}这种形式,最后一个参数是一个map,map的key即为前边占位符的名字,map的value为参数值
    HashMap<String, Object> twoGetMapEntity = new HashMap<>();
    twoGetMapEntity.put("id","1");
    ResponseEntity<String> twoGetEntity = restTemplate.getForEntity("http://localhost:6788/twoGet?id={id}", String.class,twoGetMapEntity);
    System.out.println(twoGetEntity);
    
  3. public ResponseEntity getForEntity(URI url, Class responseType)
    ResponseEntity<String> threeGetEntity = restTemplate.getForEntity(new URI("http://localhost:6788/threeGet"), String.class);
    System.out.println(threeGetEntity);
    
    ====================getForEntity=======================
    <200,{"code":1,"message":"","data":"oneGet"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Fri, 24 May 2019 01:09:43 GMT"]>
    <200,{"code":1,"message":"","data":"oneGet1--1"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Fri, 24 May 2019 01:09:43 GMT"]>
    <200,{"code":1,"message":"","data":"twoGet--1"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Fri, 24 May 2019 01:09:43 GMT"]>
    <200,{"code":1,"message":"","data":"threeGet"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Fri, 24 May 2019 01:09:43 GMT"]>
    

headForHeaders

获取请求头,用于检查对象是否存在,不返回body信息

  1. public HttpHeaders headForHeaders(String url, Object… uriVariables)
    HttpHeaders oneHeaders = restTemplate.headForHeaders("http://localhost:6788/oneGet");
    System.out.println(oneHeaders);
    
  2. public HttpHeaders headForHeaders(String url, Map<String, ?> uriVariables)
    HashMap<String, Object> headMap = new HashMap<>();
    headMap.put("id","1");
    HttpHeaders twoHeaders = restTemplate.headForHeaders("http://localhost:6788/twoGet?id={id}", headMap);
    System.out.println(twoHeaders);
    
  3. public HttpHeaders headForHeaders(URI url)
    HttpHeaders threeHeaders = restTemplate.headForHeaders(new URI("http://localhost:6788/oneGet"));
    System.out.println(threeHeaders);
    
    ====================headForHeaders=======================
    [Content-Type:"application/json;charset=UTF-8", Content-Length:"39", Date:"Fri, 24 May 2019 02:05:03 GMT"]
    [Content-Type:"application/json;charset=UTF-8", Content-Length:"42", Date:"Fri, 24 May 2019 02:05:03 GMT"]
    [Content-Type:"application/json;charset=UTF-8", Content-Length:"39", Date:"Fri, 24 May 2019 02:05:03 GMT"]
    

postForLocation

post提交,获取重定向的url,该Uri表示新资源的位置

  1. public URI postForLocation(String url, @Nullable Object request, Object… uriVariables)
    HttpEntity<Object> entity = new HttpEntity<>(null,null);//第一个参数为body参数,第二个参数为headers(请求头)
    URI oneUri = restTemplate.postForLocation("http://localhost:6788/onePost",entity);
    System.out.println(oneUri);
    URI oneUri1 = restTemplate.postForLocation("http://localhost:6788/onePost?id={id}",entity,"---1");
    System.out.println(oneUri1);
    
  2. public URI postForLocation(String url, @Nullable Object request, Map<String, ?> uriVariables)
    HttpEntity<Object> entity = new HttpEntity<>(null,null);
    HashMap<String, Object> uriMap = new HashMap<>();
    uriMap.put("id","---1");
    URI twoUri = restTemplate.postForLocation("http://localhost:6788/onePost?id={id}", entity, uriMap);
    System.out.println(twoUri);
    
  3. public URI postForLocation(URI url, @Nullable Object request)
    URI threeUri = restTemplate.postForLocation(new URI("http://localhost:6788/onePost"), entity);
    System.out.println(threeUri);
    
    ====================postForLocation=======================
    https://blog.csdn.net/YCJ_xiyang/column/info/38209
    https://blog.csdn.net/YCJ_xiyang/column/info/38209---1
    https://blog.csdn.net/YCJ_xiyang/column/info/38209---1
    https://blog.csdn.net/YCJ_xiyang/column/info/38209
    

postForObject

  1. public T postForObject(String url, @Nullable Object request, Class responseType,
    Object… uriVariables)
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    Gson gson = new Gson();
    Map<String,String> postMaps = new HashMap<>();
    postMaps.put("name","cat");
    HttpEntity<Object> postEntity = new HttpEntity<>(gson.toJson(postMaps),headers);
    String onePost = restTemplate.postForObject("http://localhost:6788/onePost",postEntity,String.class);
    System.out.println(onePost);
    String onePost1 = restTemplate.postForObject("http://localhost:6788/onePost?id={id}",postEntity,String.class,"---1");
    System.out.println(onePost1);
    
  2. public T postForObject(String url, @Nullable Object request, Class responseType,
    Map<String, ?> uriVariables)
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    Gson gson = new Gson();
    Map<String,String> postMaps = new HashMap<>();
    postMaps.put("name","cat");
    HttpEntity<Object> postEntity = new HttpEntity<>(gson.toJson(postMaps),headers);
    HashMap<String, Object> postMap = new HashMap<>();
    postMap.put("id","---1");
    String twoPost = restTemplate.postForObject("http://localhost:6788/onePost?id={id}", postEntity,String.class, postMap);
    System.out.println(twoPost);
    
  3. public T postForObject(URI url, @Nullable Object request, Class responseType)
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    Gson gson = new Gson();
    Map<String,String> postMaps = new HashMap<>();
    postMaps.put("name","cat");
    HttpEntity<Object> postEntity = new HttpEntity<>(gson.toJson(postMaps),headers);
    String threePost = restTemplate.postForObject(new URI("http://localhost:6788/onePost"), postEntity,String.class);
    System.out.println(threePost);
    
    ====================postForObject=======================
    {"code":1,"message":"","data":"onePostnull----{\"name\":\"cat\"}"}
    {"code":1,"message":"","data":"onePost---1----{\"name\":\"cat\"}"}
    {"code":1,"message":"","data":"onePost---1----{\"name\":\"cat\"}"}
    {"code":1,"message":"","data":"onePostnull----{\"name\":\"cat\"}"}
    

postForEntity

  1. public ResponseEntity postForEntity(String url, @Nullable Object request,
    Class responseType, Object… uriVariables)
    HttpHeaders postHeadersEntity = new HttpHeaders();
    postHeadersEntity.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
    body.add("name","tom");
    HttpEntity<Object> postEntitys = new HttpEntity<>(body,postHeadersEntity);
    ResponseEntity<String> onePostEntity = restTemplate.postForEntity("http://localhost:6788/onePostEntity", postEntitys, String.class);
    System.out.println(onePostEntity);
    ResponseEntity<String> onePostEntity1 = restTemplate.postForEntity("http://localhost:6788/onePostEntity?id={id}",postEntitys,String.class,"---1");
    System.out.println(onePostEntity1);
    
  2. public ResponseEntity postForEntity(String url, @Nullable Object request,
    Class responseType, Map<String, ?> uriVariables)
    HttpHeaders postHeadersEntity = new HttpHeaders();
    postHeadersEntity.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
    body.add("name","tom");
    HttpEntity<Object> postEntitys = new HttpEntity<>(body,postHeadersEntity);
    HashMap<String, Object> postMapEntity = new HashMap<>();
    postMapEntity.put("id","---1");
    ResponseEntity<String> twoPostEntity = restTemplate.postForEntity("http://localhost:6788/onePostEntity?id={id}", postEntitys,String.class, postMapEntity);
    System.out.println(twoPostEntity);
    
  3. public ResponseEntity postForEntity(URI url, @Nullable Object request, Class responseType)
    HttpHeaders postHeadersEntity = new HttpHeaders();
    postHeadersEntity.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
    body.add("name","tom");
    HttpEntity<Object> postEntitys = new HttpEntity<>(body,postHeadersEntity);
    HashMap<String, Object> postMapEntity = new HashMap<>();
    postMapEntity.put("id","---1");
    ResponseEntity<String> threePostEntity = restTemplate.postForEntity(new URI("http://localhost:6788/onePostEntity"), postEntitys,String.class);
    System.out.println(threePostEntity);
    

    扩展content-type:form-data

     HttpHeaders postHeadersEntitys = new HttpHeaders();
     postHeadersEntity.add("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE);
     MultiValueMap<String,String> bodys = new LinkedMultiValueMap<>();
     bodys.add("name","sam");
     HttpEntity<Object> postEntityss = new HttpEntity<>(bodys,postHeadersEntitys);
     ResponseEntity<String> onePostEntitys = restTemplate.postForEntity("http://localhost:6788/onePostEntity", postEntityss, String.class);
     System.out.println(onePostEntitys);
    
    ====================postForEntity=======================
    <200,{"code":1,"message":"","data":"onePostEntitynull----tom"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Tue, 28 May 2019 01:20:58 GMT"]>
    <200,{"code":1,"message":"","data":"onePostEntity---1----tom"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Tue, 28 May 2019 01:20:58 GMT"]>
    <200,{"code":1,"message":"","data":"onePostEntity---1----tom"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Tue, 28 May 2019 01:20:58 GMT"]>
    <200,{"code":1,"message":"","data":"onePostEntitynull----tom"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Tue, 28 May 2019 01:20:58 GMT"]>
    ====================postForEntity扩展=======================
    <200,{"code":1,"message":"","data":"onePostEntitynull----sam"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Tue, 28 May 2019 01:20:58 GMT"]>
    

put

put 在restful中 表示更新或创建,清楚参数和post差不多,只不过没有返回值,这里只演示一种

  1. public void put(String url, @Nullable Object request, Object… uriVariables)
    HttpHeaders putHeaders = new HttpHeaders();
    putHeaders.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<Object> putEntity = new HttpEntity<>(null,putHeaders);
    restTemplate.put("http://localhost:6788/put?id={id}",putEntity,"--1");
    
  2. public void put(String url, @Nullable Object request, Map<String, ?> uriVariables)
  3. public void put(URI url, @Nullable Object request)

patchForObject

patch接口表示修改,参数和上面的类似,不一一演示了
注意:restTemplate默认使用的jdk的HttpURLConnection,不支持patch,需要替换为Apache HttpComponents
引入依赖compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.2'

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
  1. public T patchForObject(String url, @Nullable Object request, Class responseType,
    Object… uriVariables)
    HttpHeaders patchHeaders = new HttpHeaders();
    patchHeaders.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<Object> patchEntity = new HttpEntity<>(null,patchHeaders);
    String patch = restTemplate.patchForObject("http://localhost:6788/patch?id={id}", patchEntity, String.class, "--1");
    System.out.println(patch);
    
  2. public T patchForObject(String url, @Nullable Object request, Class responseType,
    Map<String, ?> uriVariables)
  3. public T patchForObject(URI url, @Nullable Object request, Class responseType)
    ====================patchForObject=======================
    {"code":1,"message":"","data":"patch----1"}
    

delete

顾名思义:表示删除的接口,无返回值

  1. public void delete(String url, Object… uriVariables)
    restTemplate.delete("http://localhost:6788/delete?id={id}",  "--1");
    
  2. public void delete(String url, Map<String, ?> uriVariables)
  3. public void delete(URI url)
    ====================delete=======================
    [GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS]
    

optionsForAllow

询问可以执行哪些方法,参数跟上面类似,演示一种

  1. public Set optionsForAllow(String url, Object… uriVariables)
     Set<HttpMethod> httpMethods = restTemplate.optionsForAllow("http://localhost:6788/optionsForAllow?id={id}", "--1");
     System.out.println(httpMethods);
    
  2. public Set optionsForAllow(String url, Map<String, ?> uriVariables)
  3. public Set optionsForAllow(URI url)
    ====================optionsForAllow=======================
    [GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS]
    

exchange

exchange方法提供统一的方法模板进行四种请求:POST,PUT,DELETE,GET
说明:
1)url: 请求地址;
2)method: 请求类型(如:POST,PUT,DELETE,GET);
3)requestEntity: 请求实体,封装请求头,请求内容
4)responseType: 响应类型,根据服务接口的返回类型决定
5)uriVariables: url中参数变量值

  1. public ResponseEntity exchange(String url, HttpMethod method,@Nullable HttpEntity<?> requestEntity,
    Class responseType, Object… uriVariables)
  2. public ResponseEntity exchange(String url, HttpMethod method,@Nullable HttpEntity<?> requestEntity,
    Class responseType ,Map<String, ?> uriVariables )
  3. public ResponseEntity exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
    Class responseType)

前面3种,参数类似,和上面的操作相同

  1. public ResponseEntity exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
    ParameterizedTypeReference responseType, Object… uriVariables)
  2. public ResponseEntity exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
    ParameterizedTypeReference responseType, Map<String, ?> uriVariables)
  3. public ResponseEntity exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
    ParameterizedTypeReference responseType)
  4. public ResponseEntity exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference responseType)

上面4种,ParameterizedTypeReference 支持即泛型类作为返回类型
例子:ParameterizedTypeReference 例子

  1. public ResponseEntity exchange(RequestEntity<?> requestEntity, Class responseType)

    最后一种RequestEntity<?>里面加请求头,请求方法,请求地址

    //get添加请求头
    HttpHeaders exchangeHeaders = new HttpHeaders();
    exchangeHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    URI url = new URI("http://localhost:6788/exchange?id=--1");
    RequestEntity<Object> orderEntity = new RequestEntity<>(exchangeHeaders,HttpMethod.GET,url);
    ResponseEntity<String> result = restTemplate.exchange(orderEntity, String.class);
    System.out.println(result);
    ====================exchange=======================
    <200,{"code":1,"message":"","data":"exchange--1"},[Content-Type:"application/json;charset=UTF-8", Transfer-Encoding:"chunked", Date:"Tue, 28 May 2019 02:45:26 GMT"]>
    

例子源码地址

例子源码地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章