解析URL参数时的URI :: InvalidURIError

时间:2013-06-09 04:57:16

标签: ruby twitter gem

https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=# {user}& count =#{number}(URI :: InvalidURIError)

我从命令行解析的args是

name = ARGV[1]
number = ARGV[2]

会感激一些帮助...

1 个答案:

答案 0 :(得分:0)

不是尝试将值插入到URL中,而是让正确的事情让Ruby处理特殊字符的可能编码:

require 'uri'

name = 'foo'
number = 1

uri = URI('https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true')
uri.query = URI.encode_www_form(
  Hash[
    URI.decode_www_form(uri.query)
  ].merge('name' => name, 'count' => number)
)

puts uri

运行后,这是输出:

https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&name=foo&count=1

虽然有90%的时间你可以使用插值将值放入URL中,但有时候你需要包含一个需要编码的字符,当你输入时你的URL会产生错误尝试使用它。

URI类遵循关于如何编码查询的规范,因此您不会遇到这些问题。

打破它,你可以看到会发生什么:

uri.query
# => "include_entities=true&include_rts=true"
URI.decode_www_form(uri.query)
# => [["include_entities", "true"], ["include_rts", "true"]]
Hash[URI.decode_www_form(uri.query)]
# => {"include_entities"=>"true", "include_rts"=>"true"}
Hash[URI.decode_www_form(uri.query)].merge('name' => name, 'count' => number)
# => {"include_entities"=>"true", "include_rts"=>"true", "name"=>"foo", "count"=>1}
URI.encode_www_form(Hash[URI.decode_www_form(uri.query)].merge('name' => name, 'count' => number))
# => "include_entities=true&include_rts=true&name=foo&count=1"

编辑:

  

URI的未定义方法`decode_www_form':模块(NoMethodError)

     

我正在使用ruby 1.9

看看Addressable宝石。它做得非常好,并且具有内置URI类的更多功能:

require 'addressable/uri'

name = 'foo'
number = 1

uri = Addressable::URI.parse('https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true')
uri.query_values = uri.query_values.merge('name' => name, 'count' => number)

puts uri

看起来像:

https://api.twitter.com/1/statuses/user_timeline.json?count=1&include_entities=true&include_rts=true&name=foo