使用 HTTParty 解析 HTTP 标头“set-cookie”

Sve*_* R. 5 ruby-on-rails setcookie session-cookies httparty http-headers

我使用 HTTParty 来发出 HTTP 请求并使用 REST API。现在我想重新使用我通过 POST 调用的登录页面设置的 cookie。

class SomeImporter
  include HTTParty

  def self.login
    response = self.post('https://www.example.com/login', :query => {:user => 'myusername', :password => 'secret'})
    self.default_cookies.add_cookies(response.header['set-cookie'])
    self.get('https://www.example.com/protected')
  end
end
Run Code Online (Sandbox Code Playgroud)

使用此代码未正确设置 cookie。如何正确解析 HTTParty 给出的“set-cookie”标头并为下一个请求设置 cookie?

Sve*_* R. 3

Set-Cookie通常, HTTP 标头中的每个条目都有一个条目。HTTParty 将它们合并为一个字符串,作为逗号分隔的列表。但 HTTParty 在将它们添加回默认 cookie 时不会自行拆分它们。你必须自己解析它们。

可以使用以下方法解析“set-cookie”。将其添加到您的班级中:

# Parse the 'set-cookie' string
# @param [String] all_cookies_string
# @return [Hash]
def self.parse_set_cookie(all_cookies_string)
  cookies = Hash.new

  if all_cookies_string.present?
    # single cookies are devided with comma
    all_cookies_string.split(',').each {
      # @type [String] cookie_string
        |single_cookie_string|
      # parts of single cookie are seperated by semicolon; first part is key and value of this cookie
      # @type [String]
      cookie_part_string  = single_cookie_string.strip.split(';')[0]
      # remove whitespaces at beginning and end in place and split at '='
      # @type [Array]
      cookie_part         = cookie_part_string.strip.split('=')
      # @type [String]
      key                 = cookie_part[0]
      # @type [String]
      value               = cookie_part[1]

      # add cookie to Hash
      cookies[key] = value
    }
  end

  cookies
end
Run Code Online (Sandbox Code Playgroud)

通过调整此行,可以将 cookie 添加到 HTTParty 以用于以下请求:

self.default_cookies.add_cookies(self.parse_set_cookie(response.header['set-cookie']))
Run Code Online (Sandbox Code Playgroud)

self.parse_set_cookiecookie 中,仅提取名称和值。您可以扩展它以获取更多详细信息,例如PathDomain等等。有关更多详细信息,请参阅RFC 2109(4.2.2 Set-Cookie 语法)。

  • cookie 中有日期,例如“Wed”,不能用“,”分隔 (2认同)