Trouble opening utf-8 URI's with Ruby's 'open-uri'

南楼画角 提交于 2019-12-10 21:17:22

问题


I'm trying to get Danish location addresses from google maps web services API with ruby and open-uri.

Trying to get Ærø, Denmark: http://maps.googleapis.com/maps/api/geocode/json?address=ærø&sensor=false&region=dk works in Chrome does not with open-uri:

require 'rubygems'
require "open-uri"
require 'json'

uri = "http://maps.googleapis.com/maps/api/geocode/json?address=ærø&sensor=false&region=dk"
response = open(uri)
array = JSON.parse(response)
pp array

Here it yields

/usr/lib/ruby/1.8/uri/common.rb:436:in `split': bad URI(is not URI?): http://maps.googleapis.com/maps/api/geocode/json?address=ærø&sensor=false&region=dk (URI::InvalidURIError)

Another way of doing it seems to be to escape characters:

uri = "http://maps.googleapis.com/maps/api/geocode/json?address=ærø&sensor=false&region=dk"
uri_escaped = URI.escape(uri)
response = open(uri_escaped)
array = JSON.parse(response.read)
pp array

But this yields an escaped result (which is not sought after :-)

Anyone have any idea what could solve this problem (getting unescaped feedback or sending an utf-8 request)?

Ruby version here is 1.8.7


回答1:


Figured it out:

Just add

require 'string19'

to the top of the second example and it works



来源:https://stackoverflow.com/questions/7821853/trouble-opening-utf-8-uris-with-rubys-open-uri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!