Class: WeChat::Bot::HTTP::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/wechat/bot/http/session.rb

Overview

可保存 Cookies 的 HTTP 请求类

简单实现 Python 版本 requests.Session()

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bot) ⇒ Session

Returns a new instance of Session.



12
13
14
15
16
# File 'lib/wechat/bot/http/session.rb', line 12

def initialize(bot)
  @bot = bot

  load_cookies(@bot.config.cookies)
end

Instance Attribute Details

#cookiesHTTP::CookieJar (readonly)

Returns:

  • (HTTP::CookieJar)


10
11
12
# File 'lib/wechat/bot/http/session.rb', line 10

def cookies
  @cookies
end

Instance Method Details



57
58
59
60
61
62
# File 'lib/wechat/bot/http/session.rb', line 57

def cookie_of(name)
  cookies.cookies.each do |cookie|
    return cookie.value if name == cookie.name
  end
  nil
end

#delete(url, options = {}) ⇒ HTTP::Response

Returns:

  • (HTTP::Response)


34
35
36
# File 'lib/wechat/bot/http/session.rb', line 34

def delete(url, options = {})
  request(:delete, url, options)
end

#get(url, options = {}) ⇒ HTTP::Response

Returns:

  • (HTTP::Response)


19
20
21
# File 'lib/wechat/bot/http/session.rb', line 19

def get(url, options = {})
  request(:get, url, options)
end

#post(url, options = {}) ⇒ HTTP::Response

Returns:

  • (HTTP::Response)


24
25
26
# File 'lib/wechat/bot/http/session.rb', line 24

def post(url, options = {})
  request(:post, url, options)
end

#put(url, options = {}) ⇒ HTTP::Response

Returns:

  • (HTTP::Response)


29
30
31
# File 'lib/wechat/bot/http/session.rb', line 29

def put(url, options = {})
  request(:put, url, options)
end

#request(verb, url, options = {}) ⇒ HTTP::Response

Returns:

  • (HTTP::Response)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/wechat/bot/http/session.rb', line 39

def request(verb, url, options = {})
  prepare_request(url)

  if options[:timeout]
    connect_timeout, read_timeout = options.delete(:timeout)
    @client = @client.timeout(connect: connect_timeout, read: read_timeout)
  end

  response = @client.request(verb, url, options)
  update_cookies(response.cookies)

  @bot.logger.verbose "[#{verb.upcase}] #{url}"
  @bot.logger.verbose "Options: #{options}"
  @bot.logger.verbose "Response: #{response.body}"

  response
end