一. 什么是RestTemplate
Spring's central class for synchronous client-side HTTP access.
It simplifies communication with HTTP servers, and enforces RESTful principles.
It handles HTTP connections, leaving application code to provide URLs(with possible template variables) and extract results.
上面這段是RestTemplate類中的簡單介紹,RestTemplate是Spring3.0后開始提供的用于訪問 Rest 服務(wù)的輕量級客戶端,相較于傳統(tǒng)的HttpURLConnection、Apache HttpClient、OkHttp等框架,RestTemplate大大簡化了發(fā)起HTTP請求以及處理響應(yīng)的過程。本文關(guān)注RestTemplate是如何使用的,暫不涉及內(nèi)部的實現(xiàn)原理。
二.一個簡單的例子。
定義一個簡單的restful接口
@RestController public class TestController { @RequestMapping(value = "testPost", method = RequestMethod.POST) public ResponseBean testPost(@RequestBody RequestBean requestBean) { ResponseBean responseBean = new ResponseBean(); responseBean.setRetCode("0000"); responseBean.setRetMsg("succ"); return responseBean; } }