今天來(lái)學(xué)習(xí)SpringWeb中的RestTemplate, RestTemplate幫我們簡(jiǎn)化了在程序中發(fā)送http/https請(qǐng)求的大量配置, 甚至是開(kāi)箱即用, 直接new RestTemplate()便可使用.
舉個(gè)簡(jiǎn)單的例子
RestTemplate restTemplate = new RestTemplate();
Map response = restTemplate.getForObject(url, HashMap.class);
getForObject() 和 postForObject() 是比較常用的兩個(gè)方法, 顧名思義, 就是通過(guò)get/post請(qǐng)求獲取數(shù)據(jù)并封裝到指定的類(lèi)里面, 默認(rèn)restTemplate會(huì)使用Jackson封裝到對(duì)象中.
在這里順便介紹Spring另一個(gè)工具類(lèi) UriComponentsBuilder 當(dāng)我們需要封裝請(qǐng)求參數(shù)到url上面的時(shí)候, 這工具類(lèi)可以非常方便的幫我們加上參數(shù), 簡(jiǎn)單例子:
String url = "http://localhost:8088/test";
URI uri = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("msg", "lwz")
.build().toUri();
restTemplate.getForObject(uri, HashMap.class);
當(dāng)然也可以使用原生寫(xiě)法:
String url = "http://localhost:8088/test?msg={msg}";
HashMap<String, Object> uriVariables = new HashMap<>();
uriVariables.put("msg", "lwz");
restTemplate.getForObject(url, HashMap.class, uriVariables);
哪種寫(xiě)法更方便, 各位見(jiàn)仁見(jiàn)智.
今天先寫(xiě)到這, 有空再更