Ruby on rails HTTP request issue

240 views Asked by At

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:[email protected]/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:[email protected]/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.

1

There are 1 answers

3
max On

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