ruby URI类
一. URI
require 'uri' uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413") #=> #<URI::HTTP:0x00000000b14880 URL:http://foo.com/posts?id=30&limit=5#time=1305298413> uri.scheme #=> "http" uri.host #=> "foo.com" uri.path #=> "/posts" uri.query #=> "id=30&limit=5" uri.fragment #=> "time=1305298413" uri.to_s #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"
二. 常用方法
-
encode_www_form(enum, enc=nil)
URI.encode_www_form([["q", "ruby"], ["lang", "en"]]) #=> "q=ruby&lang=en" URI.encode_www_form("q" => "ruby", "lang" => "en") #=> "q=ruby&lang=en" URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en") #=> "q=ruby&q=perl&lang=en" URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]]) #=> "q=ruby&q=perl&lang=en"
-
decode_www_form(str, enc=Encoding::UTF_8, separator: '&', use__charset_: false, isindex: false)
ary = URI.decode_www_form("a=1&a=2&b=3") p ary #=> [['a', '1'], ['a', '2'], ['b', '3']] p ary.assoc('a').last #=> '1' p ary.assoc('b').last #=> '3' p ary.rassoc('a').last #=> '2' p Hash[ary] # => {"a"=>"2", "b"=>"3"}
相当于对请求字符串进行编解码
-
URI.encode(str[, unsafe])
URI.escape(str[, unsafe])
require 'uri' p URI.encode('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby参考手册')
#=> http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby%B2%CE%BF%BC%CA%D6%B2%E1
编码为URI字符串后返回结果
-
URI.unescape(str)
URI.decode(str)
require 'uri' p URI.unescape('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby%B2%CE%BF%BC%CA%D6%B2%E1') #=> http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby参考手册
解码URI字符串后返回结果