我將 Spring Boot 2.6.1 與 Spring Web MVC 一起使用,并且在我的控制器中,我想獲取接收到的資訊,RequestEntity而不僅僅是請求正文,因為我必須使用 URL 等資訊。
當我想測驗我的控制器時,我RequestEntity使用以下代碼構建一個:
RequestEntity<String> r = RequestEntity.post("http://www.example.com/{path}", "myPath").body("");
現在,我不知道如何從該 RequestEntity 檢索 URL 資訊:
r.getUrl()拋出一個,UnsupportedOperationException因為RequestEntity.
查看 中的代碼時RequestEntity.body(String),我看到回傳的物件是一個UriTemplateRequestEntity擴展RequestEntity物件,但根據其建構式,該物件似乎始終具有空 URL。僅設定uriTemplate,uriVarsArray和uriVarsMap屬性。但是這些屬性不是RequestEntity.
如何從 中檢索 URL 資訊r,而不將其轉換為UriTemplateRequestEntity?這是RequestEntity.getUrl()我應該報告的錯誤嗎?
注意:我的解決方法如下:
RequestEntity<String> r = RequestEntity.post(URI.create(format("http://www.example.com/%s", "myPath"))).body("");
或者
RequestEntity<String> r = RequestEntity.post(URI.create("http://www.example.com/{path}".replaceAll("\\{path\\}", "myPath"))).body("");
uj5u.com熱心網友回復:
HttpServletRequest在控制器引數中使用,如下所示:
@GetMapping("/")
public String test(HttpServletRequest httpReq){
String url=httpReq.getRequestURL().toString();
// More code
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397017.html
