首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析具有大括号的URI,URI::InvalidURIError:坏URI(不是URI吗?)

解析具有大括号的URI,URI::InvalidURIError:坏URI(不是URI吗?)
EN

Stack Overflow用户
提问于 2012-01-13 03:47:55
回答 2查看 2.2K关注 0票数 3

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

代码语言:javascript
复制
require 'uri'
my_uri = "http://www.anyserver.com/getdata?anyparameter={330C-B5A2}"
the_uri = URI.parse(my_uri)

发出以下错误:

代码语言:javascript
复制
URI::InvalidURIError: bad URI(is not URI?)

我需要一种与每次编码大括号不同的解决方案:

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

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

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

代码语言:javascript
复制
# 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一起使用,并且不会引发错误。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-13 15:22:40

代码语言:javascript
复制
# 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对象的实例化分配内存。

票数 5
EN

Stack Overflow用户

发布于 2012-01-13 03:53:41

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

代码语言:javascript
复制
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL.
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8845661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档