ruby - 在 URI 上设置包含 [ ] 的路径

标签 ruby uri

我正在尝试使用 URI 创建一个 uri,但似乎不接受方括号 ([]):

uri = URI.parse("http://example.com")
uri.path = URI.escape("/test[1].png")

URI::InvalidComponentError: bad component(expected absolute path component): /test[1].png
from /Users/something/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/generic.rb:823:in `check_path'

知道怎么做吗?我是否应该不使用 URI 而只是在最后转义 uri?

最佳答案

我建议使用 Addressable::URI为此。

虽然 Ruby 的内置 URI 很方便,但它显示出一些老化的迹象,我怀疑这就是其中之一。 Addressable::URI 已被提议作为 URI 的替代品,因为它符合当前的 RFC,并且功能更全。

require 'addressable/uri'
Addressable::URI.parse("http://example.com/test[1].png")
=> #<Addressable::URI:0x81404710 URI:http://example.com/test[1].png>

Addressable::URI.parse("http://example.com/test[1].png").to_s
=> "http://example.com/test[1].png"

对于简单、通用的用途,我使用 URI,只是因为。对于繁重的工作,我使用 Addressable::URI。

关于ruby - 在 URI 上设置包含 [ ] 的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739752/

相关文章:

ruby - 多线程归并排序

ruby - 字符串中的数组条目不映射到哈希

javascript - 从相机胶卷 React Native 解码 QR 码图像

android - 什么是 uri,contentValues

java - RESTful Web 服务中复合对象的 URI

css - 将元素放在全屏 flexbox 的中心和右下角?

ruby-on-rails - Rails Rake Tasks,在期间和结束时输出一条消息

ruby - 如何在 Ruby 中翻转给定的输入

C#:CommandLineParser 如何解析URL?

android - 当链接也通过深度链接重定向时在浏览器中打开