1. 程式人生 > >【Diary】【2018-10-20】【RestTemplate詳解】

【Diary】【2018-10-20】【RestTemplate詳解】

1.Get請求

第一種:getForEntity

getForEntity函式,該方法返回的是ResponseEntity,該物件是SpringHttp請求響應的封裝,其中封裝了Http的幾個重要元素,比如Http請求狀態碼的列舉物件HttpStatus,還有Http的請求頭。

RestTemplate rest=new RestTemplate();

ResponseEntity(T) response=rest.getEntity(url,T,para);

T t=response.getBody();

getEntity共實現了三個實現方法:

a.getEntity(String Url,Class responseType,Object ... urlVariables);

url為請求服務地址,type為body的包裝型別,urlVariables為一個引數的陣列,具體用法如下:

http:/url?name={1},由於urlVariables為一個數組,它會依次填充。

b.getForEntity(String Url,Class responseType,Map urlVariables);

跟上個實現方法的區別在於,第三個引數是Map,使用方法如下:

//引數 Map<String> map=new HashMap<String>();

map.put("para",para);

http:/url?name={para}

c.getForEntity(String Url,Class responseType)

第二種:getForObject

getObject是對於getEntity的二次封裝,它通過HttpMessageConverterExtractor對Http請求響應體body內容進行物件轉換。使用方法類似於三個上面的方法。

2.Post請求:

post請求跟request請求類似都有三個方法實現:

a.postForEntity(String url,Object request,Class reponseType,Object...uriVariables);

b.postForEntity(String url,Object request,Class reponseType,Map uriVariables);

c.postForEntity(String url,Object request,Class reponseType);

跟get請求的方法類似,uriVariables對於url請求引數的繫結。

postForObject跟get請求方法類似

與get請求不同的地方在於post提供了postForLocation函式,將提交的post請求,並且返回新資源的uri.

同時也擁有三個過載方法,跟上面三個類似。

PUT請求

put請求的三個方法同上類似,只不過put請求為viod型別

a.put(String url,Object request,Object...urlVariables);

b.put(String url,Object request,Map urlVariables);

c.put(String url,Object request);

DELETE請求

delete同上也有三個不同的請求方法,因為delete方法通常把唯一標識拼接在url中,所以delete一般不需要request請求引數

a.delete(String url,Object...urlVariables);

b.delete(String url,Map urlVariables);

c.delete(String url);