简体   繁体   中英

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

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

Figured it out:

Just add

require 'string19'

to the top of the second example and it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM