RestTemplate中幾種常見請求方法的使用

2021-10-14 08:45:55 字數 2379 閱讀 8843

在resttemplate中,傳送乙個get請求,我們可以通過如下兩種方式:

getforentity方法的返回值是乙個responseentityresponseentity是spring對http請求響應的封裝,包括了幾個重要的元素,如響應碼、contenttype、contentlength、響應訊息體等。比如下面乙個例子:

public string gethello()

關於這段**,我說如下幾點:

最終顯示結果如下:

有時候我在呼叫服務提供者提供的介面時,可能需要傳遞引數,有兩種不同的方式,如下:

public string sayhello() ", string.class, "張三");

return responseentity.getbody();

}public string sayhello2() ", string.class, map);

return responseentity.getbody();}

public string sayhello3() ").build().expand("王五").encode();

uri uri = uricomponents.touri();

responseentityresponseentity = resttemplate.getforentity(uri, string.class);

return responseentity.getbody();}

通過spring中提供的uricomponents來構建uri即可。

當然,服務提供者不僅可以返回string,也可以返回乙個自定義型別的物件,比如我的服務提供者中有如下方法:

public book book1()

對於該方法我可以在服務消費者中通過如下方式來呼叫:

public book book1()

執行結果如下:

getforobject函式實際上是對getforentity函式的進一步封裝,如果你只關注返回的訊息體的內容,對其他資訊都不關注,此時可以使用getforobject,舉乙個簡單的例子,如下:

public book book2()

getforobject也有幾個過載方法,如下:

這幾個過載方法引數的含義和getforentity一致,我就不再贅述了。

在resttemplate中,post請求可以通過如下三個方法來發起:

該方法和get請求中的getforentity方法類似,如下例子:

public book book3()

我這裡建立了乙個book物件,這個book物件只有name屬性有值,將之傳遞到服務提供者那裡去,服務提供者**如下:

public book book2(@requestbody book book)

服務提供者接收到服務消費者傳來的引數book,給其他屬性設定上值再返回,呼叫結果如下:

postforentity的其他過載方法如下:

這些方法的引數含義和getforentity引數的含義一致,不再贅述。

如果你只關注,返回的訊息體,可以直接使用postforobject。用法和getforobject一致。

postforlocation也是提交新資源,提交成功之後,返回新資源的uri,postforlocation的引數和前面兩種的引數基本一致,只不過該方法的返回值為uri,這個只需要服務提供者返回乙個uri即可,該uri表示新資源的位置。

在resttemplate中,put請求可以通過put方法呼叫,put方法的引數和前面介紹的postforentity方法的引數基本一致,只是put方法沒有返回值而已。舉乙個簡單的例子,如下:

public void put() ", book, 99);}

book物件是我要提交的引數,最後的99用來替換前面的佔位符

delete請求我們可以通過delete方法呼叫來實現,如下例子:

public void delete() ", 100);}

delete方法也有幾個過載的方法,不過過載的引數和前面基本一致,不贅述。

RestTemplate中幾種常見的請求方式

getforentity方法的返回值是乙個responseentity,responseentity是spring對http請求響應的封裝,包括了幾個重要的元素,如響應碼 contenttype contentlength 響應訊息體等。可以用乙個數字做佔位符,最後是乙個可變長度的引數,來一一替換前...

關於RestTemplate幾種常見的方式

spring中使用rest資源,借助這個可以輕鬆訪問資源,大多是與http互動的方法 getforobject 傳送乙個http get請求,返回的請求體將對映為乙個物件 postforentity post 資料到乙個url,返回包含乙個物件的responseentity,這個物件是從響應體中對映...

Spring中RestTemplate的使用

1 帶引數的get請求 請求url示例 http localhost 8080 test sendsms?phone 手機號 msg 簡訊內容 錯誤使用 autowired private restoperations restoperations public void test throws e...