王筝的博客
ruby学习

网址中的汉字无法直接解析,需要先encode才行, 看报错说明

irb(main):043:0> url=”http://10.103.xx.xx/cms/api/module/data?name=资讯频道战略观察子频道&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223″
=> “http://10.103.xx.xx/cms/api/module/data?name=资讯频道战略观察子频道&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223″
irb(main):044:0> response = RestClient.get(url)
URI::InvalidURIError: bad URI(is not URI?): http://10.103.xx.xx/cms/api/module/data?name=资讯频道战略观察子频道&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223

safeurl = URI.encode(url.strip)

response = RestClient.get(safeurl)

irb(main):047:0> safeurl.class
=> String

==============

再转一遍就改变类型了

irb(main):048:0> aaa= URI.parse(URI.encode(url.strip))
=> #<URI::HTTP:0x0000000714a008 URL:http://10.103.xx.xx/cms/api/module/data?name=%E8%B5%84%E8%AE%AF%E9%A2%91%E9%81%93%E6%88%98%E7%95%A5%E8%A7%82%E5%AF%9F%E5%AD%90%E9%A2%91%E9%81%93&appkey=300&timestamp=1412997443&sign=72c7de8c0cf6c5e5ca0aaa11a56e6223>
irb(main):049:0> aaa.class
=> URI::HTTP
irb(main):050:0> response = RestClient.get(aaa)
NoMethodError: undefined method `match’ for #<URI::HTTP:0x0000000714a008>
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:275:in `parse_url’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:280:in `parse_url_with_auth’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:175:in `execute’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient/request.rb:41:in `execute’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/rest-client-1.7.2/lib/restclient.rb:65:in `get’
from (irb):50
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/railties-3.0.8/lib/rails/commands/console.rb:44:in `start’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/railties-3.0.8/lib/rails/commands/console.rb:8:in `start’
from /home/wangzheng/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/railties-3.0.8/lib/rails/commands.rb:23:in `<top (required)>’
from script/rails:7:in `require’
from script/rails:7:in `<main>’