我什么时候应该转义网址?
我有一个 URL 并使用以下方法转义它:
url = "http://ec4.images-xxx.com/images/I/41-%2B6wMiewL._SL135_.jpg"
url = URI.escape(url)
puts url => "http://ec4.images-xxx.com/images/I/41-%252B6wMiewL._SL135_.jpg"
从结果中我可以看到 URI 再次转义了之前转义的 %2B
,变成了 %252B
,这是不正确的。
我想知道如何确定何时应该对一个 URL 进行转义。或者,有没有一种聪明的方法,知道什么时候该逃,什么时候不该逃?
I have a URL and escaped it using:
url = "http://ec4.images-xxx.com/images/I/41-%2B6wMiewL._SL135_.jpg"
url = URI.escape(url)
puts url => "http://ec4.images-xxx.com/images/I/41-%252B6wMiewL._SL135_.jpg"
From the result I can see that URI escaped the previously escaped %2B
again which became %252B
, which is not correct.
I want to know how to make sure when one URL should be escaped. Or, is there a smart method that knows when to escape and when not to escape?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第一个字符串已经正确进行了 URI 编码,因此当您尝试对其进行重新编码时,URI.escape 方法将使用“%25”对“%”进行编码(“+”的 URI 编码)。
如果您确实不确定您的字符串是否经过 URI 编码,您可以尝试先对其进行解码,然后将其与原始字符串进行比较。如果它们相同,则尚未编码。
Your first string is already properly URI encoded, so when you try to re-encode it, the URI.escape method is encoding the '%' with '%25' (URI encoding for '+').
If you're really not sure whether your string has been URI encoded or not, you could try to decode it first, and compare it with the original. If they're the same, then it hasn't been encoded.