java - 为什么 javax.ws.rs.core.UriBuilder、fromUri() 方法在主机名 URI 末尾添加额外的 "/"?

标签 java uri

我正在尝试根据 OAuth2 授权代码流的请求生成重定向 URI。该请求包含主机名以及范围和授权代码。示例:

redirect_uri=myapp2://oauth2redirect&scope=email+profile

所以,这里的主机名是:myapp2://oauth2redirect

现在,当我执行以下代码为应用程序生成重定向 uri 时,它会在末尾添加一个额外的“/”(斜杠),而不是继续使用查询参数,即:

myapp2://oauth2redirect/?code=abcdefghijkl 

myapp2://oauth2redirect/? 中的额外/不需要的“/”导致重定向失败。 理想情况下应该是: myapp2://oauth2redirect?code=abcdefghijkl&scope=

public Response getResponse() {
    String uri = oAuthrequest.getRedirectURI();

    UriBuilder uriBuilder = UriBuilder.fromUri(uri)
                        .queryParam("code", code);

    if (oAuthrequest.getState() != null) {
        uriBuilder.queryParam("state", oAuthrequest.getState());
    }

    if(scopeNames != null && scopeNames.size() > 0) {
        uriBuilder.queryParam("scope", StringUtil.toSingleString(scopeNames, " "));
    }

    logger.info("OAuth2 Authorization response success");

    return Response.status(302).cookie(cookies).location(uriBuilder.build()).build();
}

我认为 UriBuilder.fromUri(uri) 方法在 uri 中添加了额外的“/”,因为我已经调试并检查了字符串字段“uri”的值是否正确。但是,一旦执行此行,它就会在 uri 后面添加额外的“/”,然后继续附加查询参数。

最佳答案

好吧,我想出了一个 hacky 解决方案:鉴于 getRedirectURI() 将返回类似 "myapp2://oauth2redirect"

// builds an URI object from the URI string
java.net.URI uri = java.net.URI.create(getRedirectURI());

// uses the authory(oauth2redirect) as the path to build the uri
UriBuilder uriBuilder = UriBuilder.fromPath(
            // forcefully adds the double slashes (//), without this, 
            // at this point, the uri would be: myapp2:oauth2redirect
            "//" + uri.getAuthority())
            .scheme(uri.getScheme());

uriBuilder.queryParam("code", "myCode");

uriBuilder.build(); // produces the uri: myapp2://oauth2redirect?code=myCode

关于java - 为什么 javax.ws.rs.core.UriBuilder、fromUri() 方法在主机名 URI 末尾添加额外的 "/"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44801925/

相关文章:

java - 错误原因 - Jsoup.isValid

java - 如何将 String 转换为从 sqlite 获取的 Uri 并将其设置在 ImageView 中?

android - 让 googlemaps 接受本地 KML 文件?

c# - 用于更改链接的 HtmlAgilityPack 示例不起作用。我该如何做到这一点?

java - 单击图像时出现 “Element is not clickable at point” - Selenium WebDriver Java

java - 创建多边形时如何在顶点之间添加n个点

android - 在 Android MediaStore 中插入音频专辑

php - CodeIgniter 中的 URI 路由

java - "while running the android game app"在 logcat 中给出警告信息

java - spring mvc - 服务器启动时出错 - apache tomcat