【问题标题】:Parsing URIs that have curly braces, URI::InvalidURIError: bad URI(is not URI?)解析带有大括号的 URI,URI::InvalidURIError: bad URI(is not URI?)
【发布时间】:2012-02-09 08:47:59
【问题描述】:

使用 ruby​​ 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 一起使用,并且不会引发错误。

【问题讨论】:

  • 为什么一定要用URI解析呢?您是否正在使用 URI 对 URL 进行其他操作,或者是否有其他必须编码的参数?
  • 是的,基本上我正在修改一个广泛使用它的 gem,并且替换所有代码并不是很好,所以我更喜欢在一个地方更改 URI#parse 行为:)

标签: ruby parsing uri ruby-1.9.2 curly-braces


【解决方案1】:

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.

【讨论】:

  • 谢谢!,但我没有太多选择,因为 uri 是由不完全遵循 RFC 的外部服务提供的,所以还是使用了花括号 :)
【解决方案2】:
# 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 对象的实例化分配内存。

【讨论】:

    猜你喜欢
    • 2017-12-18
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2012-02-23
    • 2011-07-19
    相关资源
    最近更新 更多