我正在尝试使用 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/