如何对 URI 参数值进行编码?
我想发送 URI 作为查询/矩阵参数的值。 在将其附加到现有 URI 之前,我需要根据 RFC 2396 对其进行编码。例如,给定输入:
http://google.com/resource?key=value1 & value2
我期望输出:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2
两者都不是java.net.URLEncoder
和 java.net.URI 都不会生成正确的输出。 URLEncoder
用于 HTML 表单编码,与 RFC 2396 不同。URI
没有一次编码单个值的机制,因此它无法知道value1 和 value2 是同一键的一部分。
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:
http://google.com/resource?key=value1 & value2
I expect the output:
http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2
Neither java.net.URLEncoder
nor java.net.URI
will generate the right output. URLEncoder
is meant for HTML form encoding which is not the same as RFC 2396. URI
has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Jersey 的 UriBuilder 使用应用程序对 URI 组件进行编码/x-www-form-urlencoded 和 RFC 3986(根据需要)。 根据 Javadoc
Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc
您还可以使用 Spring 的 UriUtils
You could also use Spring's UriUtils
我没有足够的声誉来评论答案,但我只是想指出,单独下载 JSR-311 api 是行不通的。 您需要下载参考实现 (jersey)。
当 api 尝试在运行时查找实现时,仅从 JSR 页面下载 api 才会出现 ClassNotFoundException。
I don't have enough reputation to comment on answers, but I just wanted to note that downloading the JSR-311 api by itself will not work. You need to download the reference implementation (jersey).
Only downloading the api from the JSR page will give you a ClassNotFoundException when the api tries to look for an implementation at runtime.
我自己写的,很短,超级简单,如果你愿意,你可以复制它:
http://www.dmurph.com/2011/01/java-uri-编码器/
I wrote my own, it's short, super simple, and you can copy it if you like:
http://www.dmurph.com/2011/01/java-uri-encoder/
似乎 CharEscapers 来自 Google GData-java-client 有你想要的。 它有 uriPathEscaper 方法、uriQueryStringEscaper 和通用 uriEscaper。 (所有返回执行实际转义的 Escaper 对象)。 阿帕奇许可证。
It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.
我认为 URI 类就是您正在寻找的那一位。
I think that the URI class is the one that you are looking for.
嗯,我知道你已经放弃了 URLEncoder,但不管文档怎么说,我还是决定尝试一下。
你说:
所以:
正如预期的那样。
这会出现什么问题呢?
Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.
You said:
So:
As expected.
What would be the problem with this?