2

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?

2
  • try to encode the URL first before passing to HTTParty Commented Aug 10, 2013 at 3:24
  • I tried and failed. It must be something I have missed. Could please show me some code? Commented Aug 10, 2013 at 6:15

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This works. But I get can't convert HTTParty::Response into String when using it. See my update
Well. You do not have to now. It seems like I have found the solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.