使用新的Spring UriComponentsBuilder进行URL编码 [英] URL encoding using the new Spring UriComponentsBuilder

查看:2166
本文介绍了使用新的Spring UriComponentsBuilder进行URL编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用spring的UriComponentsBuilder生成用于oauth交互的一些url.查询参数包括诸如回调URL和带有空格的参数值之类的实体.

I'm attempting to use spring's UriComponentsBuilder to generate some urls for oauth interaction. The query parameters include such entities as callback urls and parameter values with spaces in them.

尝试使用UriComponentBuilder(因为现已弃用UriUtils)

Attempting to use UriComponentBuilder (because UriUtils is now deprecated)

UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(oauthURL);
urlBuilder.queryParam("client_id", clientId);
urlBuilder.queryParam("redirect_uri", redirectURI);
urlBuilder.queryParam("scope", "test1 test2");

String url = urlBuilder.build(false).encode().toUriString();

不幸的是,虽然scope参数中的空格已成功用'+'替换,但redirect_uri参数根本没有经过url编码.

Unfortunately, while the space in the scope parameter is successfully replaced with '+', the redirect_uri parameter is not at all url encoded.

例如

redirect_uri=https://oauth2-login-demo.appspot.com/code

应该已经结束

redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Fcode

但没有被触及.深入研究代码,尤其是org.springframework.web.util.HierarchicalUriComponents.Type.QUERY_PARAM.isAllowed(c):

but was untouched. Diving into the code, specifically org.springframework.web.util.HierarchicalUriComponents.Type.QUERY_PARAM.isAllowed(c) :

if ('=' == c || '+' == c || '&' == c) {
  return false;
}
else {
  return isPchar(c) || '/' == c || '?' == c;
}

清楚地允许使用':'和'/'字符,而按口香糖则不允许.它一定在做其他类型的编码,尽管对于我一生来说,我无法想象.我在这里树错树了吗?

clearly allows ':' and '/' characters, which by gum, it shouldn't. It must be doing some other type of encoding, though for the life of me, I can't imagine what. Am I barking up the wrong tree(s) here?

谢谢

推荐答案

UriComponentsBuilder根据 RFC 3986 ,其中有关URI的查询"部分的第3.4节要特别注意.

UriComponentsBuilder is encoding your URI in accordance with RFC 3986, with section 3.4 about the 'query' component of a URI being of particular note.

在查询"组件中,允许使用字符"/"和:",并且无需转义.

Within the 'query' component, the characters '/' and ':' are permitted, and do not need escaping.

以'/'字符为例:'query'组件(明显由未转义的'?'和(可选)'#'字符分隔)不是分层的,并且'/'字符没有特殊含义意义.因此它不需要编码.

To take the '/' character for example: the 'query' component (which is clearly delimited by unescaped '?' and (optionally) '#' characters), is not hierarchical and the '/' character has no special meaning. So it doesn't need encoding.

这篇关于使用新的Spring UriComponentsBuilder进行URL编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆