要点在于 Net::HTTP.new("example.com").get(url, headers)
的时候 headers
中调用 cookie 方法,在没有 @cookie
变量的时候就登录,然后后期如果得到的返回是 302, (如果 302 代表需要登录). 那就清除 @cookie
变量再 retry
require "net/http"
module PubPage
class HTTP
class << self
def get(path)
@@instance ||= self.new
@@instance.get(path)
end
end
def get(path)
uri = URI(path)
url = "#{uri.path}?#{uri.query}"
resp = http.get(url, headers)
raise NeedLoginException if resp.code == "302"
resp
rescue NeedLoginException
@cookie = nil
retry
end
private
def http
@http ||= Net::HTTP.new("example.com")
end
def headers
{ "Cookie" => cookie }
end
def login_data
config = YAML.load_file(Pow(Rails.root, "config/pub_page.yml"))
account = config["account"]
password = config["password"]
"action=login&loginName=#{account}&pwd=#{password}"
end
def login
@cookie = http
.post("/login.json", login_data)
.get_fields('set-cookie')
.select {|e|
e.match(/SESSION_ID/)
}.map {|e|
e.split(/; /)[0]
}.first
end
def cookie
login unless @cookie
@cookie
end
end
end