
一. 什么是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類中的簡(jiǎn)單介紹,RestTemplate是Spring3.0后開(kāi)始提供的用于訪問(wèn) Rest 服務(wù)的輕量級(jí)客戶端,相較于傳統(tǒng)的HttpURLConnection、Apache HttpClient、OkHttp等框架,RestTemplate大大簡(jiǎn)化了發(fā)起HTTP請(qǐng)求以及處理響應(yīng)的過(guò)程。本文關(guān)注RestTemplate是如何使用的,暫不涉及內(nèi)部的實(shí)現(xiàn)原理。
二.一個(gè)簡(jiǎn)單的例子。
定義一個(gè)簡(jiǎ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;
}
}