如何检索从 RequestEntity.post(String, Object...) 获得的 RequestEntity 的 URL
How to retrieve the URL of a RequestEntity obtained from RequestEntity.post(String, Object...)
我正在使用 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
.
中没有 URL
查看 RequestEntity.body(String)
中的代码时,我发现返回的对象是 UriTemplateRequestEntity
扩展 RequestEntity
,但这个对象似乎总是有一个 null URL 根据其构造函数。仅设置 uriTemplate
、uriVarsArray
和 uriVarsMap
属性。但是这些属性不是 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
}
我正在使用 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
,但这个对象似乎总是有一个 null URL 根据其构造函数。仅设置 uriTemplate
、uriVarsArray
和 uriVarsMap
属性。但是这些属性不是 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
}