spring詳解 RestTemplate 操作

當(dāng)我們從服務(wù)消費(fèi)端去調(diào)用服務(wù)提供者的服務(wù)的時(shí)候,使用了一個(gè)很好用的對(duì)象,叫做RestTemplate,接下來我們?cè)敿?xì)的對(duì)RestTemplate的用法做一下解析

1.本文主要從以下常用的2個(gè)方面來看RestTemplate的使用:

GET請(qǐng)求 POST請(qǐng)求

1.GET請(qǐng)求

在RestTemplate中,發(fā)送一個(gè)GET請(qǐng)求,我們可以通過如下兩種方式:

第一種:getForEntity和getForObject

(1)getForEntity方法的返回值是一個(gè)ResponseEntity,ResponseEntity是Spring對(duì)HTTP請(qǐng)求響應(yīng)的封裝,包括了幾個(gè)重要的元素,如響應(yīng)碼、contentType、contentLength、響應(yīng)消息體等。
(2)getForObject() 方法用來只獲取 響應(yīng)體信息.
getForObject 和 getForEntity 用法幾乎相同,只是返回值返回的是 響應(yīng)體,省去了我們 再去 getBody()
(3)自我感覺,一般代碼中應(yīng)使用getForEntity方法,我們可以先判斷響應(yīng)碼,然后再去獲取請(qǐng)求體,個(gè)人意見,不喜勿噴,在這里,我們只講getForEntity方法的使用。

無參數(shù)的 getForObject 請(qǐng)求

   public List<UserEntity> getAll2() {
       ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://localhost/getAll", List.class);
       HttpHeaders headers = responseEntity.getHeaders();
       HttpStatus statusCode = responseEntity.getStatusCode();
       int code = statusCode.value();
       //statusCode.is2xxSuccessful();判斷狀態(tài)碼是否為2開頭的

       List<UserEntity> list = responseEntity.getBody();

       System.out.println(list.toString());
       return list;

   }

注意,返回值是List就是List.class,返回值是對(duì)象,就寫對(duì)應(yīng)的對(duì)象

有時(shí)候我在調(diào)用服務(wù)提供者提供的接口時(shí),可能需要傳遞參數(shù),有兩種不同的方式,如下:

@RequestMapping("/sayhello")
public String sayHello() {
    ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={1}", String.class, "張三");
    return responseEntity.getBody();
}
@RequestMapping("/sayhello2")
public String sayHello2() {
    Map<String, String> map = new HashMap<>();
    map.put("name", "李四");
    ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/sayhello?name={name}", String.class, map);
    return responseEntity.getBody();
}
  • 可以用一個(gè)數(shù)字做占位符,最后是一個(gè)可變長(zhǎng)度的參數(shù),來一一替換前面的占位符
  • 也可以前面使用name={name}這種形式,最后一個(gè)參數(shù)是一個(gè)map,map的key即為前邊占位符的名字,map的value為參數(shù)值
  • 如果你想對(duì)一個(gè)參數(shù)用一個(gè)URL來代替一長(zhǎng)串的字符串,那你只能用UriComponents來構(gòu)建你的URL
@RequestMapping("/sayhello3")
public String sayHello3() {
    UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://HELLO-SERVICE/sayhello?name={name}").build().expand("王五").encode();
    URI uri = uriComponents.toUri();
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
    return responseEntity.getBody();
}

2.Post請(qǐng)求

(1)了解了get請(qǐng)求后,Post請(qǐng)求就變得很簡(jiǎn)單了,第一個(gè)參數(shù)是 URL,第二個(gè)參數(shù)是入?yún)?,第三個(gè)參數(shù)是返回參數(shù),第四個(gè)參數(shù)如果有的話是URL后邊拼接的東西

   // 有參數(shù)的 postForEntity 請(qǐng)求
    @RequestMapping("saveUserByType/{type}")
    public String save2(UserEntity userEntity,@PathVariable("type")String type) {

        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class, type);
        String body = responseEntity.getBody();

        return body;

    }

    // 有參數(shù)的 postForEntity 請(qǐng)求,使用map封裝
    @RequestMapping("saveUserByType2/{type}")
    public String save3(UserEntity userEntity,@PathVariable("type")String type) {
        HashMap<String, String> map = new HashMap<>();
         map.put("type", type);


        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/saveByType/{type}", userEntity, String.class,map);
        String body = responseEntity.getBody();

        return body;

    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,533評(píng)論 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,933評(píng)論 1 92
  • 簡(jiǎn)介 Spring Cloud Ribbon是一個(gè)基于HTTP和TCP的客戶端負(fù)載均衡工具,它基于Netflix ...
    Chandler_玨瑜閱讀 252,175評(píng)論 22 183
  • 1.你如何看待舊人?A.舊人是劣等種族必將滅絕。B.舊人有一定能力應(yīng)該被圈養(yǎng)。 可兒看著這道題,愣了一下,這是什么...
    刀疤兒閱讀 474評(píng)論 0 2
  • 今天晚上,我們?nèi)タ戳艘粓?chǎng)盛大的表演,又見敦煌講了絲綢之路中敦煌從古至今的變化。 其中,第三募是一女睡在榻上,那...
    初二3班楊英杰閱讀 507評(píng)論 0 0

友情鏈接更多精彩內(nèi)容