Question

My problem is with the request headers.

This is a little script I cooked up which doesn't work:

require 'httparty'
require 'highline/import'

#Login.new.post lets us log in. Everything works up to the subreddits method.

class Login
  include HTTParty
  base_uri 'www.reddit.com'
#So far, so good.

  def post(username, password)
    options = {:body => {:user => username, :passwd => password, :api_type => 'json'}}
    self.class.post("/api/login/#{username}", options)
  end

#I think this part is right, in and of itself. The problem is in how the headers
#are composed (which is why I keep bonking my head on the wall.)
  def subreddits(headers)
    self.class.get("/reddits/mine", headers)
  end

  def cli_user_login(user, password)
    a = Login.new.post(user, password);
    puts a;
    #We logged in and got some JSON with an empty errors array and, nestled deep, a cookie.
    reddit_session = a["json"]["data"]["cookie"]
    #Just putting the cookie in a variable. Print it to make sure it's there:
    puts reddit_session
    #reddit_session displays, no problem. We HAVE the cookie.
  b = Login.new.subreddits("headers" => {"reddit_session" => reddit_session})
  puts b
  #Then suddenly it spits out a mountain of html....... but not the subreddits! :(
  end

end


##The following is just for testing, because I'm whimsical or stupid or something
class IWouldLikeToPlayAGame
  def initialize
    puts "PLEASE ETNER YOUR REDDIT CRITERIALS"
    a = gets.chomp.strip
    b = ask("PLEASE BE ENTERING YOUR RREDDIT password"){ |q| q.echo = false }

    Login.new.cli_user_login(a, b)
  end
end

IWouldLikeToPlayAGame.new

I think my error is around line 30. My headers hash looks like this:

{"headers" => {"reddit_session" => cookie}}

GET reddit.com/reddits/mine.xml with that header and I should have the subreddit listing, right?

Was it helpful?

Solution

First you need to specify format extension for data that you want to get, xml or json:

/reddits/mine.extension

Second you need to send reddit_session in cookies hash, not headers:

:cookies => {'reddit_session' => reddit_session}

Semicolons in ruby are optional, better to omit them.

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