如何检索从 RequestEntity.post(字符串,对象..)获取的请求实体的URL



我正在使用Spring Boot 2.6.1和Spring Web MVC,在我的控制器中,我想获取收到的RequestEntity,而不仅仅是请求正文,因为我必须使用URL等信息。

当我想测试我的控制器时,我使用以下代码构建一个RequestEntity

RequestEntity<String> r = RequestEntity.post("http://www.example.com/{path}", "myPath").body("");

现在,我不知道如何从该请求实体中检索 URL 信息:

r.getUrl()抛出UnsupportedOperationException,因为RequestEntity中没有 URL。

在查看RequestEntity.body(String)中的代码时,我看到返回的对象是一个扩展RequestEntityUriTemplateRequestEntity,但是根据其构造函数,该对象似乎总是有一个空URL。仅设置uriTemplateuriVarsArrayuriVarsMap属性。但这些属性不是RequestEntity的一部分。

如何从r中检索URL信息,而不将其转换为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("");

在控制器参数中使用HttpServletRequest,如下所示:

@GetMapping("/")
public String test(HttpServletRequest httpReq){
String url=httpReq.getRequestURL().toString();
// More code
}

最新更新