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"]>
    

例子源碼地址

例子源碼地址

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