springboot 整合 RestTemplate 與 使用方法
RestTemplate 的 postForObject 方法有四個參數
- String url => 顧名思義 這個參數是請求的url路徑
- Object request => 請求的body 這個參數需要再controller類用 @RequestBody 注解接收
- Class<T> responseType => 接收響應體的類型
- ------------ 第四個參數 postForObject 方法多種重構
- Map<String,?> uriVariables => uri 變量 顧名思義 這是放置變量的地方
- Object... uriVariables => 可變長 Object 類型 參數
首先我們使用最簡單的一種 可變長Object 參數 進行傳值
@Service public class HelloService { @Autowired RestTemplate restTemplate; public String helloService(String name,Integer age){ return restTemplate.postForObject("http://SERVICE-HELLO/hello?name={name}&age={age}", null, String.class, name,age); } }
需要再url上拼接參數並使用{參數名}占位符站位
然后將參數放到 第四個參數 可變長 Object 參數上 即可
Controller類代碼
@RestController public class DemoController { @Value("${server.port}") String port; @PostMapping("hello") public String home(String name,Integer age){ return "hello " + name + " you age is " + age + " ,i am from port:" + port; } }
測試
返回成功
接下來我們使用 Map傳值
public String helloService(String name,Integer age){ Map<String,Object> map = new HashMap<>(); map.put("name",name); map.put("age",age); return restTemplate.postForObject("http://SERVICE-HELLO/hello?name={name}&age={age}", null, String.class, map); }
只需要將參數放入到map中即可
那有些人要問了 , 為什么不能用 第二個 request 參數傳值 , 其實是可以的
我試過用HashMap 和 LinkedHashMap 都是接收不到的
所以我們來看一下源碼是怎么寫的
首先進入到 postForObject 方法中 發現request 參數 傳入了一個 httpEntityCallBack 方法中 , 那么接着追蹤
進入httpEntityCallBack方法中
httpEntityCallBack方法又調用了 RestTemplate的HttpEntityRequestCallback方法
進入HttpEntityRequestCallback
這里會出現一個分支 instanceof 類型判定 requestBody 參數是否是 HttpEntity類型
如果不是則 創建一個HttpEntity類將 requestBody 參數傳入
那么我們來看一下 HttpEntity 是怎么個構造
這里可以看到 HttpEntity 有兩個構造方法 一個是 傳入 泛型的body 另一個是傳入 MultiValueMap<String,String> headers
那么 這個MultiValueMap 是個什么東東
百度一下 發現 MultiValueMap 可以讓一個key對應多個value,感覺是value產生了鏈表結構,可以很好的解決一些不好處理的字符串問題
找到 MultiValueMap 接口的實現類
這里我們使用 LinkedMultiValueMap
public String helloService(String name,Integer age){ MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(); paramMap.add("name",name); paramMap.add("age", age); return restTemplate.postForObject("http://SERVICE-HELLO/hello",paramMap,String.class); }
Controller代碼
public class DemoController { @Value("${server.port}") String port; @PostMapping("hello") public String home(String name,Integer age){ return "MultiValueMap : hello " + name + " you age is " + age + " ,i am from port:" + port; } }
測試
返回值正確 操作成功