I’m using Spring Boot 2.6.1 with Spring Web MVC, and in my controller, I want to get the received RequestEntity
instead of only the request body, because I have to use information such as the URL.
When I want to test my controller, I build a RequestEntity
with the following code:
RequestEntity<String> r = RequestEntity.post("http://www.example.com/{path}", "myPath").body("");
Now, I don’t know how to retrieve the URL information from that RequestEntity:
r.getUrl()
throws an UnsupportedOperationException
because there is no URL in the RequestEntity
.
When looking at the code in RequestEntity.body(String)
, I see that the returned object is an UriTemplateRequestEntity
extending RequestEntity
, but this object seems to always have an null URL according to its constructor. Only the uriTemplate
, uriVarsArray
and uriVarsMap
attributes are set. But these attributes are not part of RequestEntity
.
How can I retrieve the URL information from r
, without casting it to an UriTemplateRequestEntity
? Is that a bug in RequestEntity.getUrl()
I should report?
NB: My workaround is the following:
RequestEntity<String> r = RequestEntity.post(URI.create(format("http://www.example.com/%s", "myPath"))).body("");
or
RequestEntity<String> r = RequestEntity.post(URI.create("http://www.example.com/{path}".replaceAll("\{path\}", "myPath"))).body("");
Advertisement
Answer
Use HttpServletRequest
in controller parameter like below:
@GetMapping("/") public String test(HttpServletRequest httpReq){ String url=httpReq.getRequestURL().toString(); // More code }