使用红宝石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一起使用,并且不会引发错误。
发布于 2012-01-13 15:22:40
# 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-13 03:53:41
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.https://stackoverflow.com/questions/8845661
复制相似问题