2

我正在尝试使用外部 API 来获取一些信息

  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)

但是,address是中文的,所以我需要转换成UTF-8代码,如果不是我会得到URI::InvalidURIError (bad URI(is not URI?):怎么做?

我试过address=self.address.force_encoding('utf-8')了,但它不起作用,也许我应该改用其他方法?

更新:

  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']

我明白了can't convert HTTParty::Response into String。它出什么问题了?

我在这里找到了一些东西,我想我需要明确告诉 Httparty 用 JSON 解析它?

4

1 回答 1

2

您可以将其保存到文件“geo.rb”并运行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)
于 2013-08-10T09:16:16.933 回答