How to get 302 redirect location in Rails? (have tried HTTParty, Net/Http and RedirectFollower)

StackOverflow https://stackoverflow.com/questions/4379700

Question

Hello
i am trying to get Facebook user's album's cover picture.
as it's said in the API page, it returns "An HTTP 302 with the URL of the album's cover picture" when getting:
http s://graph.facebook.com/[album_id]}/picture?access_token=blahblahblah...
documents here: http://developers.facebook.com/docs/reference/api/album

i've tried HTTParty, Net:HTTP and also the RedirectFollower class
HTTParty returns the picture image itself, and no "location" (URL) information anywhere
NET:HTTP and RedirectFollower are a bit tricky...
if i don't use URI.encode when passing the URL into the get method, it causes "bad uri" error
but if i use URI.encode to pass the encoded URI, it causes EOFError (end of file reached)
what's amazing is that i can see the location URL when using apigee's FB API

here is the redirect method which is recommended on the Net:HTTP documents:
anything should be modified? or is there any easier way to do this? thank you!!

def self.fetch(uri_str, limit = 10)
  response = Net::HTTP.get_response(URI.parse(uri_str))
  case response
    when Net::HTTPSuccess     then response
    when Net::HTTPRedirection then fetch(response['location'], limit - 1)
  else
    response.error!
  end
end
Was it helpful?

Solution 2

here is what i end up with after some trial and error:

uri_str = URI.encode(https://graph.facebook.com/[album_id]}/picture?access_token=blahblahblah...)

result = Curl::Easy.http_get(uri_str) do |curl|
  curl.follow_location = false
end
puts result.header_str.split('Location: ')[1].split(' ')[0]

the returned header_str looks like
"HTTP blah blah blah Location: http://xxxxxxx/xxxx.jpg blah blah blah"
so i managed to get the URL by using 2 split()
the final result is a clean URL
also the curl.follow_location should be false so it won't return the body of that page

OTHER TIPS

If you don't mind using a gem, curb will do this for you. It's all about using the follow_location parameter:

gem 'curb'
require 'curb'

# http://www.stackoverflow.com/ redirects to http://stackoverflow.com/

result = Curl::Easy.http_get("http://www.stackoverflow.com/") do |curl|
 curl.follow_location = true
end

puts result.body_str

This is not the only library with this feature, though.

As a note, many times you will get an invalid location in the header and it will have to be interpreted by the user agent to render it into something useful. A header like Location: / will need to be re-written before it can be fetched. Other times you will get a header like Location: uri=... and you'll have to pull out the location from there. It's really best to leave it to your library than re-write that yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top