Rails: How to send a http get request with UTF-8 encoding - ruby-on-rails

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?

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)

Related

Net::HTTP::Post fails while calling spaces url with argument error

I have this code to send notifications to google spaces from my Rails code. The notifications are going out but one of the lines gives error. I tried with different ways of calling it but strange it keep failing in the mid.
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://chat.googleapis.com/v1/spaces/AAAAAAAAA/messages?key=AIzaSyDddsdHDSDS-WEfzqKqqsHI&token=OaX6LQKRyIC8aSUXH8cnuKZXAII%3D")
header = {'Content-Type': 'application/json'}
data = {
"text": "Bijendra-Test Notification!"
}
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = data.to_json
response = http.request(request)
Error:
request = Net::HTTP::Post.new(uri.request_uri, header)
Traceback (most recent call last):
ArgumentError (wrong number of arguments calling `method` (given 1, expected 0))
Since request is initialized with this error, it gets the body in next line of code and send the notification.
Rails - 5.2, jruby-9.3.3.0
Your exact code with a URL I can access (URI.parse("https://httpbin.org/anything?id=anotherthing")) gives me no errors on jruby 9.3.3.0 or C Ruby 2.7.6.
(I get a 400 API key error for your chat.googleapis URL, which I assume is correct)
That makes me think that the problem is the specific response you're getting from Google vs the parsing that net/http does.
To confirm this, you can try with the same URL I used. If that works, then it's worth posting a sanitised version of the google response so that people here can help you understand what the specific issue is.

Ruby on rails HTTP request issue

I am an newbie to Ruby on Rails. I have a url which points to a JSON output. When I ran the URL directly like http://user:pass#myurl.com/json, I am getting the response without any authendication. However http://myurl.com/json requires a username and password through a standard apache pop up authentication box. I have tried to access this URL from my rails controller like the following:
result = JSON.parse(open("http://user:pass#myurl.com/json").read)
When I try to do, I just get an error which says ArgumentError, userinfo not supported. [RFC3986]
Also I have tried the below one. I am getting a 401-Unauthorized error
open("http://...", :http_basic_authentication=>[user, password])
How can I make a request that works in this case. Any help would be appreciated.
You need to use Net::HTTP (or some other HTTP client).
require 'net/http'
require 'uri'
require 'json'
uri = URI('http://myurl.com/json')
req = Net::HTTP::Get.new( uri )
req.basic_auth 'user', 'pass'
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
result = JSON.parse(res.body)
puts result

Bad URI with Ruby

I am making an Oauth call to the Facebook API to get myself an access_token
def access_token
token_uri = URI("https://graph.facebook.com/oauth/access_token?client_id=#{CLIENT_ID}&client_secret=#{CLIENT_SECRET}&grant_type=client_credentials")
token_response = HTTParty.get(token_uri)
Rails.logger.info(token_response)
return token_response
end
I get a response and a access_token generated, let's say it's
access_token=123456789|abcdefghijk
but when I then try to use this token
def get_feed
fb_access_token = access_token
uri = URI("https://graph.facebook.com/#{VANDALS_ID}/posts/?#{fb_access_token}")
end
I get an error
URI::InvalidURIError: bad URI(is not URI?)
and the uri generated stops at the | even though there are more characters after the pipe to complete my access_key
https://graph.facebook.com/id-here/posts/?access_token=123456789|
How do I get the full access token available in my URI?
The reason you are getting an error is that | symbol is not allowed in the proper URI, hence it needs to be escaped before it's parsed. URI comes with a method to do it for you:
uri = URI(URI.escape "https://graph.facebook.com/#{VANDALS_ID}/posts/?#{fb_access_token}")
uri.to_s #=> https://graph.facebook.com/id-here/posts/?access_token=123456789%7Cabcdefghijk
When the url is requested, the server should automatically decode it, so all should work as expected.

Rails/Ruby equivalent of PHP file_get_contents

Would like to know the Rails/Ruby equivalent of the following PHP:
$data = json_decode(file_get_contents(URL_GOES_HERE))
The URL is an external resource that returns json data (Facebook's API).
I've tried:
data = JSON.parse(URL_GOES_HERE)
but I assume I still need the `file_get_contents' part? How do I do this in Rails 4?
Try this
require 'open-uri'
file = open(URL_GOES_HERE)
data = JSON.parse file.read

Setting outgoing IP address in open-uri with RoR

I'm new to open-uri and trying to set an outgoing IP address using open-uri in ruby on rails. I used this post as a reference to get started. I'm porting an app from PHP where I could use CURLOPT_INTERFACE in curl_setopt. What's the best way to do this using open-uri in rails? (Doing this from the controller - not command line.)
If there's not a way to do this - any suggestions on an alternative to open-uri? My goal is to take in and parse JSON data.
What I understand from your questions is you want to hit another server from a specific IP which suggests you have a server with couple of addresses.
What I can suggest you is try to execute curl directly and do what you want to do or use a wrapper for it.
Doesn't look like open-uri can do this. But with net/https it's fairly easy.
require 'net/https'
require 'json'
uri = URI('https://jsonvat.com/')
http = Net::HTTP.new(uri.host, uri.port)
http.local_host = '1.2.3.4'
http.use_ssl = true
request = Net::HTTP::Get.new('/')
request.content_type = 'application/json'
request.initialize_http_header('Content-Type' => 'application/json')
response = http.request(request)
json = JSON.parse(response.body)
Probably you don't need the "require" lines inside Rails Controllers.
You can specify the outgoing IP address with the http.local_host line.
https://stackoverflow.com/a/24896074/1371731
https://yukimotopress.github.io/http

Resources