最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot下使用RestTemplate實現(xiàn)遠程服務調(diào)用的詳細過程

 更新時間:2025年08月11日 11:36:23   作者:嗨嗨人生。  
RestTemplate是Spring框架中封裝HTTP請求的同步工具,支持GET、POST、PUT、DELETE等方法,提供exchange通用請求方式,簡化網(wǎng)絡調(diào)用并提升開發(fā)效率,本文給大家介紹SpringBoot下使用RestTemplate實現(xiàn)遠程服務調(diào)用的詳細過程,感興趣的朋友一起看看吧

現(xiàn)如今的項目,由服務端向外發(fā)起網(wǎng)絡請求的場景,基本上處處可見。

RestTemplate是一個執(zhí)行HTTP請求的同步阻塞式工具類,它僅僅只是在 HTTP 客戶端庫(例如 JDK HttpURLConnection,Apache HttpComponents,okHttp 等)基礎上,封裝了更加簡單易用的模板方法 API,方便程序員利用已提供的模板方法發(fā)起網(wǎng)絡請求和處理,能很大程度上提升我們的開發(fā)效率

1、前置配置

在spring環(huán)境下使用RestTemplate

如果當前項目是SpringBoot,添加SpringBoot啟動依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

同時,將RestTemplate配置初始化為一個Bean對象

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

注意:在這種初始化方法,是使用了JDK自帶的HttpURLConnection作為底層HTTP客戶端實現(xiàn)。

在需要使用RestTemplate的位置,注入并使用即可!

@Autowired
private RestTemplate restTemplate;

2、API實戰(zhàn):

RestTemplate最大的特色就是對各種網(wǎng)絡請求方式做了包裝,能極大的簡化開發(fā)人員的工作量,下面我們以GET、POST、PUT、DELETE為例,分別介紹各個API的使用方式

2.1 GET請求:

2.1.1 不帶參的get請求

@RestController
public class TestController {
    /**
     * 不帶參的get請求
     * @return
     */
    @RequestMapping(value = "testGet", method = RequestMethod.GET)
    public User testGet(){
        User user = new User();
        user.setCode("200");
        user.setMsg("請求成功,方法:testGet");
        return user;
    }
}
@Data
public class User {
    private String code;
    private String msg;
}
@Autowired
private RestTemplate restTemplate;
/**
 * 單元測試(不帶參的get請求)
 */
@Test
public void testGet(){
    //請求地址
    String url = "http://localhost:8080/testGet";
    //發(fā)起請求,直接返回對象
    User user = restTemplate.getForObject(url, User.class);
}

2.1.2 帶參的get請求(使用占位符號傳參)

@RestController
public class TestController {
    /**
     * 帶參的get請求(restful風格)
     * @return
     */
    @RequestMapping(value = "testGetByRestFul/{id}/{name}", method = RequestMethod.GET)
    public User testGetByRestFul(@PathVariable(value = "id") String id, @PathVariable(value = "name") String name){
        User user = new User();
        user.setCode("200");
        user.setMsg("請求成功,方法:testGetByRestFul,請求參數(shù)id:" +  id + "請求參數(shù)name:" + name);
        return user;
    }
}
@Autowired
private RestTemplate restTemplate;
 /**
 * 單元測試(帶參的get請求)
 */
@Test
public void testGetByRestFul(){
    //請求地址
    String url = "http://localhost:8080/testGetByRestFul/{1}/{2}";

    //發(fā)起請求,直接返回對象(restful風格)
    User user = restTemplate.getForObject(url, User.class, "001", "張三");
}

2.1.3 帶參的get請求(restful風格)

@RestController
public class TestController {
    /**
     * 帶參的get請求(restful風格)
     * @return
     */
    @RequestMapping(value = "testGetByParam", method = RequestMethod.GET)
    public User testGetByParam(@RequestParam("userName") String userName,
                                             @RequestParam("userPwd") String userPwd){
        User user = new User();
        user.setCode("200");
        user.setMsg("請求成功,方法:testGetByParam,請求參數(shù)userName:" +  userName + ",userPwd:" + userPwd);
        return user;
    }
}
@Autowired
private RestTemplate restTemplate;
 /**
 * 單元測試(帶參的get請求)
 */
@Test
public void testGetByParam(){
    //請求地址
    String url = "http://localhost:8080/testGetByParam?userName={userName}&userPwd={userPwd}";
    //請求參數(shù)
    Map<String, String> uriVariables = new HashMap<>();
    uriVariables.put("userName", "唐三藏");
    uriVariables.put("userPwd", "123456");
    //發(fā)起請求,直接返回對象(帶參數(shù)請求)
    User user = restTemplate.getForObject(url, User.class, uriVariables);
}

2.1.4 getForEntity使用示例

上面的所有的getForObject請求傳參方法,getForEntity都可以使用,使用方法上也幾乎是一致的,只是在返回結(jié)果接收的時候略有差別。

使用ResponseEntity<T> responseEntity來接收響應結(jié)果。用responseEntity.getBody()獲取響應體。

/**
 * 單元測試
 */
@Test
public void testAllGet(){
    //請求地址
    String url = "http://localhost:8080/testGet";
    //發(fā)起請求,返回全部信息
    ResponseEntity<User> response = restTemplate.getForEntity(url, User.class);
    // 獲取響應體
    System.out.println("HTTP 響應body:" + response.getBody().toString());
    // 以下是getForEntity比getForObject多出來的內(nèi)容
    HttpStatus statusCode = response.getStatusCode();
    int statusCodeValue = response.getStatusCodeValue();
    HttpHeaders headers = response.getHeaders();
    System.out.println("HTTP 響應狀態(tài):" + statusCode);
    System.out.println("HTTP 響應狀態(tài)碼:" + statusCodeValue);
    System.out.println("HTTP Headers信息:" + headers);
}

header設置參數(shù)

//請求頭
HttpHeaders headers = new HttpHeaders();
headers.add("token", "123456789");
//封裝請求頭
HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange('請求的url', HttpMethod.GET, formEntity, String.class);

2.2 GET請求:

其實POST請求方法和GET請求方法上大同小異,RestTemplatePOST請求也包含兩個主要方法:

  • postForObject():返回body對象
  • postForEntity():返回全部的信息

2.2.1 模擬表單請求

模擬表單請求,post方法測試

@RestController
public class TestController {
    /**
     * 模擬表單請求,post方法測試
     * @return
     */
    @RequestMapping(value = "testPostByForm", method = RequestMethod.POST)
    public User testPostByForm(@RequestParam("userName") String userName,
                                        @RequestParam("userPwd") String userPwd){
        User user = new User();
        user.setCode("200");
        user.setMsg("請求成功,方法:testPostByForm,請求參數(shù)userName:" + userName + ",userPwd:" + userPwd);
        return user;
    }
}
@Autowired
private RestTemplate restTemplate;
/**
 * 模擬表單提交,post請求
 */
@Test
public void testPostByForm(){
    //請求地址
    String url = "http://localhost:8080/testPostByForm";
    // 請求頭設置,x-www-form-urlencoded格式的數(shù)據(jù)
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    //提交參數(shù)設置
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("userName", "唐三藏");
    map.add("userPwd", "123456");
    // 組裝請求體
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
    //發(fā)起請求
    User user = restTemplate.postForObject(url, request, User.class);
}

2.2.2 模擬表單請求,post方法測試(接收對象)

@RestController
public class TestController {
    /**
     * 模擬表單請求,post方法測試
     * @param request
     * @return
     */
    @RequestMapping(value = "testPostByFormAndObj", method = RequestMethod.POST)
    public User testPostByForm(UserVO request){
        User user = new User();
        user.setCode("200");
        user.setMsg("請求成功,方法:testPostByFormAndObj,請求參數(shù):" + JSON.toJSONString(request));
        return user;
    }
}
@Data
public class UserVO {
   private String userName;
   private String userPwd;
}
@Autowired
private RestTemplate restTemplate;
/**
 * 模擬表單提交,post請求
 */
@Test
public void testPostByForm(){
    //請求地址
    String url = "http://localhost:8080/testPostByFormAndObj";
    // 請求頭設置,x-www-form-urlencoded格式的數(shù)據(jù)
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    //提交參數(shù)設置
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("userName", "唐三藏");
    map.add("userPwd", "123456");
    // 組裝請求體
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
    //發(fā)起請求
    User user = restTemplate.postForObject(url, request, User.class);
}

2.2.3 模擬JSON請求,post方法測試

@RestController
public class TestController {
    /**
     * 模擬JSON請求,post方法測試
     * @param request
     * @return
     */
    @RequestMapping(value = "testPostByJson", method = RequestMethod.POST)
    public User testPostByJson(@RequestBody UserVO request){
        User user = new User();
        user.setCode("200");
        user.setMsg("請求成功,方法:testPostByJson,請求參數(shù):" + JSON.toJSONString(request));
        return user;
    }
}
@Autowired
private RestTemplate restTemplate;
/**
 * 模擬JSON提交,post請求
 */
@Test
public void testPostByJson(){
    //請求地址
    String url = "http://localhost:8080/testPostByJson";
    //入?yún)?
    UserVO vo = new UserVO();
    vo.setUserName("唐三藏");
    vo.setUserPwd("123456789");

    //發(fā)送post請求,并打印結(jié)果,以String類型接收響應結(jié)果JSON字符串
    ResponseBean responseBean = restTemplate.postForObject(url, vo, User.class);
}

2.3 PUT請求

put請求方法,可能很多人都沒用過,它指的是修改一個已經(jīng)存在的資源或者插入資源,該方法會向URL代表的資源發(fā)送一個HTTP PUT方法請求,示例如下

@RestController
public class TestController {
    /**
     * 模擬JSON請求,put方法測試
     * @param request
     * @return
     */
    @RequestMapping(value = "testPutByJson", method = RequestMethod.PUT)
    public void testPutByJson(@RequestBody UserVO request){
        System.out.println("請求成功,方法:testPutByJson,請求參數(shù):" + JSON.toJSONString(request));
    }
}
@Autowired
private RestTemplate restTemplate;
/**
 * 模擬JSON提交,put請求
 */
@Test
public void testPutByJson(){
    //請求地址
    String url = "http://localhost:8080/testPutByJson";
    //入?yún)?
    UserVO request = new UserVO();
    request.setUserName("唐三藏");
    request.setUserPwd("123456789");

    //模擬JSON提交,put請求
    restTemplate.put(url, request);
}

2.4 DELETE請求

與之對應的還有delete方法協(xié)議,表示刪除一個已經(jīng)存在的資源,該方法會向URL代表的資源發(fā)送一個HTTP DELETE方法請求。

@RestController
public class TestController {
    /**
     * 模擬JSON請求,delete方法測試
     * @return
     */
    @RequestMapping(value = "testDeleteByJson", method = RequestMethod.DELETE)
    public void testDeleteByJson(){
        System.out.println("請求成功,方法:testDeleteByJson");
    }
}
@Autowired
private RestTemplate restTemplate;
/**
 * 模擬JSON提交,delete請求
 */
@Test
public void testDeleteByJson(){
    //請求地址
    String url = "http://localhost:8080/testDeleteByJson";

    //模擬JSON提交,delete請求
    restTemplate.delete(url);
}

2.5 Exchange方法

如果以上方法還不滿足你的要求。在RestTemplate工具類里面,還有一個exchange通用協(xié)議請求方法,它可以發(fā)送GET、POST、DELETE、PUT、OPTIONS、PATCH等等HTTP方法請求。

到此這篇關于SpringBoot下使用RestTemplate實現(xiàn)遠程服務調(diào)用的詳細過程的文章就介紹到這了,更多相關SpringBoot RestTemplate遠程服務調(diào)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java延時任務實現(xiàn)方案及四大典型場景詳解(適用于Spring?Boot3)

    Java延時任務實現(xiàn)方案及四大典型場景詳解(適用于Spring?Boot3)

    在Java編程中,延時函數(shù)是一種常用的技術,用于在程序執(zhí)行過程中暫停一段時間,這篇文章主要介紹了Java延時任務實現(xiàn)方案及四大典型場景(適用于SpringBoot3)的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2026-05-05
  • RabbitMQ消息總線方式刷新配置服務全過程

    RabbitMQ消息總線方式刷新配置服務全過程

    Spring Cloud Bus通過消息總線與MQ實現(xiàn)微服務配置統(tǒng)一刷新,結(jié)合Git Webhooks自動觸發(fā)更新,避免手動重啟,提升效率與可靠性,適用于配置管理及全局信息同步場景
    2025-07-07
  • Java之JSF框架案例詳解

    Java之JSF框架案例詳解

    這篇文章主要介紹了Java之JSF框架案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-09-09
  • redisson特性及優(yōu)雅實現(xiàn)示例

    redisson特性及優(yōu)雅實現(xiàn)示例

    這篇文章主要為大家介紹了redisson特性及優(yōu)雅實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • Java實戰(zhàn)員工績效管理系統(tǒng)的實現(xiàn)流程

    Java實戰(zhàn)員工績效管理系統(tǒng)的實現(xiàn)流程

    只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+Mysql+Maven+HTML實現(xiàn)一個員工績效管理系統(tǒng),大家可以在過程中查缺補漏,提升水平
    2022-01-01
  • Java獲取此次請求URL以及服務器根路徑的方法

    Java獲取此次請求URL以及服務器根路徑的方法

    這篇文章主要介紹了Java獲取此次請求URL以及服務器根路徑的方法,需要的朋友可以參考下
    2015-08-08
  • Java矢量隊列Vector使用示例

    Java矢量隊列Vector使用示例

    Vector類實現(xiàn)了一個動態(tài)數(shù)組。和ArrayList很相似,但是兩者是不同的Vector是同步訪問的;Vector包含了許多傳統(tǒng)的方法,這些方法不屬于集合框架
    2023-01-01
  • SpringBoot?UserAgentUtils獲取用戶瀏覽器的用法

    SpringBoot?UserAgentUtils獲取用戶瀏覽器的用法

    UserAgentUtils是于處理用戶代理(User-Agent)字符串的工具類,一般用于解析和處理瀏覽器、操作系統(tǒng)以及設備等相關信息,這些信息通常包含在接口請求的?User-Agent?字符串中,本文介紹SpringBoot?UserAgentUtils獲取用戶瀏覽器的用法,感興趣的朋友一起看看吧
    2025-04-04
  • java servlet手機app訪問接口(三)高德地圖云存儲及檢索

    java servlet手機app訪問接口(三)高德地圖云存儲及檢索

    這篇文章主要為大家詳細介紹了java servlet手機app訪問接口(三),高德地圖云存儲及檢索,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-12-12
  • Mybatis的mapper.xml中if標簽test判斷的用法說明

    Mybatis的mapper.xml中if標簽test判斷的用法說明

    這篇文章主要介紹了Mybatis的mapper.xml中if標簽test判斷的用法說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06

最新評論

吴桥县| 汾阳市| 大石桥市| 电白县| 屯昌县| 翁源县| 潼关县| 海南省| 阜平县| 台南市| 巴林左旗| 凤城市| 布尔津县| 克山县| 巴南区| 彰化市| 黄龙县| 大方县| 太湖县| 广饶县| 杨浦区| 原平市| 临潭县| 德江县| 浦城县| 专栏| 信宜市| 赤水市| 黄山市| 浦北县| 通海县| 江孜县| 手机| 淄博市| 丹江口市| 桃江县| 吴川市| 象山县| 株洲市| 灯塔市| 麦盖提县|