3

使用红宝石 1.9.2-p290。我在尝试解析 URI 时遇到了一个问题,如下所示:

require 'uri'
my_uri = "http://www.anyserver.com/getdata?anyparameter={330C-B5A2}"
the_uri = URI.parse(my_uri)

发出以下错误:

URI::InvalidURIError: bad URI(is not URI?)

我需要一个不同的解决方案,而不是每次像这样编码花括号:

new_uri = URI.encode("http://www.anyserver.com/getdata?anyparameter={330C-B5A2}")
=> "http://www.anyserver.com/getdata?anyparameter=%7B330C-B5A2%7D"

现在我可以像往常一样解析 new_uri,但每次我需要它时都必须这样做。无需每次都这样做的最简单方法是什么?

我发布了我自己的解决方案,因为我没有完全按照我解决它的方式看到它。


# Accepts URIs when they contain curly braces
# This overrides the DEFAULT_PARSER with the UNRESERVED key, including '{' and '}'
module URI
  def self.parse(uri)
    URI::Parser.new(:UNRESERVED => URI::REGEXP::PATTERN::UNRESERVED + "\{\}").parse(uri)
  end
end

现在我可以将 URI.parse(uri) 与包含大括号的 uri 一起使用,并且不会引发错误。

4

2 回答 2

5
# Need to not fail when uri contains curly braces
# This overrides the DEFAULT_PARSER with the UNRESERVED key, including '{' and '}'
# DEFAULT_PARSER is used everywhere, so its better to override it once
module URI
  remove_const :DEFAULT_PARSER
  unreserved = REGEXP::PATTERN::UNRESERVED
  DEFAULT_PARSER = Parser.new(:UNRESERVED => unreserved + "\{\}")
end

跟进同样的问题,因为 DEFAULT_PARSER 无处不在,最好将其完全替换为 URI#parse 方法。此外,这避免了每次为新 Parser 对象的实例化分配内存。

于 2012-01-13T15:22:40.940 回答
2

RFC 1738 - http://www.faqs.org/rfcs/rfc1738.html意味着您必须对大括号进行编码

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL.
于 2012-01-13T03:53:41.613 回答