我的问题在于请求标题。
这是我编写的一个小脚本,不起作用:
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列表,对吗?
答案 0 :(得分:0)
首先,您需要为要获取的数据xml
或json
指定格式扩展名:
/reddits/mine.extension
其次,您需要在Cookie哈希中发送reddit_session
,而不是标题:
:cookies => {'reddit_session' => reddit_session}
红宝石中的分号是可选的,最好省略它们。