为什么javax.ws.rs.core.UriBuilder的fromUri()方法会添加一个额外的/&引用;在主机名URI的末尾?
我试图从OAuth2授权代码流的请求中生成重定向URI。请求包含主机名、作用域和授权代码。例如:为什么javax.ws.rs.core.UriBuilder的fromUri()方法会添加一个额外的/&引用;在主机名URI的末尾?,java,uri,Java,Uri,我试图从OAuth2授权代码流的请求中生成重定向URI。请求包含主机名、作用域和授权代码。例如: redirect_uri=myapp2://oauth2redirect&scope=email+profile 因此,这里的主机名是:myapp2://oauth2redirect // builds an URI object from the URI string java.net.URI uri = java.net.URI.create(getRedirectURI()); /
redirect_uri=myapp2://oauth2redirect&scope=email+profile
因此,这里的主机名是: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
现在,当我执行下面的代码为应用程序生成重定向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后面加上额外的“/”,然后再添加查询参数。好吧,我想出了一个骇人的解决方案:假设
getRedirectURI()
将返回类似于“myapp2://oauth2redirect”的内容。
您正在使用哪个UriBuilder?@LeonardoPina它是Jersey的UriBuilder(javax.ws.rs.core.UriBuilder)我相信问题出在URI中:
myapp2://oauth2redirect&scope=email+profile
,因为没有?
标识参数,整个oauth2redirect&scope=email+profile
被解释为URI的authority字符串URI=oAuthrequest.getRedirectURI()
方法实际获取基本url:myapp2://oauth2redirect
,并且单独获取范围。正如我所说,数据是正确的,但是当代码:UriBuilder-UriBuilder=UriBuilder.fromUri(uri).queryParam(“code”,code)代码>被执行,url中第一个查询参数的“/”代替了“?”。我想我得到了答案,检查答案=)如果uri是=myapp2://oauth2redirect/
,那么测试用例的uri以“/”结尾如何?在这种情况下,它将删除结尾处的“/”,这实际上是uri的一部分,同样的答案也适用,您只需跳过添加参数