Question

I'm trying to use an external API to get some information

  address=self.address
  response = HTTParty.get("http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a")
  decode_response =  ActiveSupport::JSON.decode(response)

However, the address is in chinese, so I need to convert into UTF-8 code, if not I'll get URI::InvalidURIError (bad URI(is not URI?): How to do it?

I tried address=self.address.force_encoding('utf-8'), but it does not work, maybe I should use other method instead?

UPDATE:

  uri = "http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a"
  encoded_uri = URI::encode(uri)
  response = HTTParty.get(encoded_uri)
  decode_response =  ActiveSupport::JSON.decode(response)
  self.latitude = decode_response['result']['location']['lat']

and I get can't convert HTTParty::Response into String. What's wrong with it?

I found something here, I think I'll need to tell Httparty explicityly to parse it with JSON?

Was it helpful?

Solution

You could save this to a file 'geo.rb' and run ruby geo.rb

require 'uri'
require 'httparty'

address = "中国上海"
uri = "http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a"
encoded_uri = URI::encode uri
puts HTTParty.get(encoded_uri)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top