解析带有花括号的URI,URI :: InvalidURIError:错误的URI(不是URI吗?) [英] Parsing URIs that have curly braces, URI::InvalidURIError: bad URI(is not URI?)

查看:479
本文介绍了解析带有花括号的URI,URI :: InvalidURIError:错误的URI(不是URI吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using ruby 1.9.2-p290. I came across an issue trying to parse a URI like the following:

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?)

与每次这样对花括号进行编码相比,我需要一个不同的解决方案:

I require a different solution than encoding the curly braces every time like this:

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

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

Now I can parse the new_uri as usual, but had to do this every time I needed it. What is the simplest way to achieve this without doing it every time?

我发布了自己的解决方案,因为我没有完全解决这个问题.

I post my own solution as I hadn't seen this exactly as I solved it.

# 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一起使用,并且不会引发任何错误.

Now I can use URI.parse(uri) with uri containing curly braces and no error is thrown.

推荐答案

# 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对象的实例化分配内存.

Following up the same issue, since DEFAULT_PARSER is used everywhere, its better to substitute it completely insted of just for the URI#parse method. Additionally this avoids allocating memory for the instantiation of a new Parser object every time.

这篇关于解析带有花括号的URI,URI :: InvalidURIError:错误的URI(不是URI吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆