I'm trying to pull an image from imgur using the provided API with Ruby 2.0.0 and Rails 4.0.0. I've tried constructing an http request in various ways as listed in the Ruby 2.0.0 docs to no avail.
Here's the code:
require 'net/http'
require 'net/https'
def imgur
headers = {
"Authorization" => "Client-ID " + my_client_id
}
path = "/3/gallery/image/#{img_id}.json"
uri = URI("https://api.imgur.com"+path)
request, data = Net::HTTP::Get.new(path, headers)
response = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(request) }
puts "response:"
p response
puts response
end
where img_id
and my_client_id
are just hardcoded with appropriate values. (imgur
method is called within a controller action corresponding to my site's root url)
This is the response I get back when I run rails s
(so I'm using localhost:3000) and then visit the root url, localhost:3000 (which does call the action that calls imgur
):
#<Net::HTTPBadRequest 400 Bad Request readbody=true>
#<Net::HTTPBadRequest:0x007f8a6ce0da78>
UPDATE:
Also, this worked:
curl --header "Authorization: Client-ID my_client_id" https://api.imgur.com/3/gallery/image/7x98w9T.json
(again, my_client_id
is hardcoded with my actual client ID). Now to get it to work on Ruby...
Anyone know the right way to do this?
You need to enable https to make an https call.
http.use_ssl = true
I know this was figured out, but I figured I'd add an explicit answer.
As @VladtheImpala pointed out, the issue is with SSL. Though I included https
in the URI string, the HTTP request was not in fact using SSL. Here's the code where I explicitly set the HTTP request to use SSL:
require 'net/http'
require 'net/https'
def imgur
puts "Let's get some pics"
headers = {
"Authorization" => "Client-ID my_client_id"
}
#http = Net::HTTP.new("https://api.imgur.com")
path = "/3/gallery/image/7x98w9T.json"
uri = URI.parse("https://api.imgur.com"+path)
request, data = Net::HTTP::Get.new(path, headers)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(request)
puts response.body
end
Works like a charm ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With