1

我的问题是请求标头。

这是我编写的一个小脚本,它不起作用:

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

我认为我的错误在第 30 行左右。我的标题哈希如下所示:

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

GET reddit.com/reddits/mine.xml有了那个标题,我应该有 subreddit 列表,对吧?

4

1 回答 1

0

首先,您需要为要获取的数据指定格式扩展名,xml或者json

/reddits/mine.extension

其次,您需要发送reddit_sessioncookie 哈希,而不是标题:

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

ruby 中的分号是可选的,最好省略它们。

于 2012-05-25T07:19:22.053 回答