如何在不编码哈希的情况下使用 URIbuilder 构建 URI

How to build a URI using URIbuilder without encoding hash

我有这样一个 URI:

java.net.URI location = UriBuilder.fromPath("../#/Login").queryParam("token", token).build();

我将其作为回复发送:return Response.seeOther(location).build()

但是,在上面的 URI 中,# 被编码为 %23/。如何在不对散列 # 进行编码的情况下创建 URI。根据 official document,必须使用 fragment() 方法来保持未编码。

URI templates are allowed in most components of a URI but their value is restricted to a particular component. E.g.

UriBuilder.fromPath("{arg1}").build("foo#bar"); would result in encoding of the '#' such that the resulting URI is "foo%23bar". To create a URI "foo#bar" use UriBuilder.fromPath("{arg1}").fragment("{arg2}").build("foo", "bar") instead.

查看文档中的示例,我不确定如何在我的案例中应用它。

最终的 URI 应如下所示:

http://localhost:7070/RTH_Sample14/#Login?token=eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcnRoLmNvbSIsInN1YiI6IlJUSCIsInJvbGUiOiJVU0VSIiwiZXhwIjoxNDU2Mzk4MTk1LCJlbWFpbCI6Imtpcml0aS5rOTk5QGdtYWlsLmNvbSJ9.H3d-8sy1N-VwP5VvFl1q3nhltA-htPI4ilKXuuLhprxMfIx2AmZZqfVRUPR_tTovDEbD8Gd1alIXQBA-qxPBcxR9VHLsGmTIWUAbxbyrtHMzlU51nzuhb7-jXQUVIcL3OLu9Gcssr2oRq9jTHWV2YO7eRfPmHHmxzdERtgtp348

使用片段构建 URI

UriBuilder.fromPath("http://localhost:7070/RTH_Sample14/").fragment("Login").build()

这导致 URI 字符串

http://localhost:7070/RTH_Sample14/#Login

但是如果你也加上查询参数

UriBuilder.fromPath("http://localhost:7070/RTH_Sample14/").fragment("Login")
          .queryParam("token", "t").build()

然后 UriBuilder 总是在片段之前插入查询参数:

http://localhost:7070/RTH_Sample14/?token=t#Login

它完全符合 URL 语法。

无需对哈希值进行编码即可避免所有重定向的麻烦。我将代码更改为以下内容:

java.net.URI location = new java.net.URI("../#/Login?token=" + token);

所以上面的查询参数是附加到 URI 位置的标记。在前端,我使用 angular 的 location.search().token 来获取查询参数。

这对我有用。寻找更好的答案。谢谢