使用HTTParty解析HTTP标头'set-cookie'

时间:2016-03-31 09:57:19

标签: ruby-on-rails http-headers session-cookies setcookie httparty

我正在使用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

此代码未正确设置Cookie。 如何正确解析HTTParty给出的'set-cookie'标题并为下一个请求设置cookie?

3 个答案:

答案 0 :(得分:2)

通常,HTTP标头中的每个Set-Cookie都有一个条目。 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

通过调整此行,可以将Cookie添加到HTTParty以便跟踪请求:

self.default_cookies.add_cookies(self.parse_set_cookie(response.header['set-cookie']))

self.parse_set_cookie范围内,Cookie仅以名称和值提取。您可以对其进行扩展,以获取更多详细信息,例如PathDomain等。有关详细信息,请参阅RFC 2109(4.2.2 Set-Cookie语法)。

答案 1 :(得分:0)

def cookies_to_hash(acookies)
    vs = acookies.split(',')
    ak = Array.new
    # Avoiding break in expiry date comma
    vs.each_cons(2) do |v, vn|
        unless(vn.include?("="))
            ak << "#{v}#{vn}"
        else
            ak << v if(v.include?("="))
        end
    end
    # Cookies as array of hashes
    all_cookies = []
    ak.each do |each_cookie|
        ecookie = []
        each_cookie.split(';').each do |cookie_attr|
            ecookie << cookie_attr.split("=")
        end
        all_cookies << Hash[ecookie]
    end
    all_cookies
end

上述方法可帮助您将响应标头中的 set-cookies 转换为有效的哈希数组。在到期时处理额外逗号的问题。

答案 2 :(得分:0)

由于@dineshspabu,我可以遵循他的模式并添加一些修改以处理到期日期。希望有帮助:

def cookies_to_hash(set_cookie)
  set_cookie = set_cookie.gsub(/Expires=[a-zA-Z]+,/) do |m|
    # replace , with #####
    m[0..-2] + "#####"
  end
  set_cookie = set_cookie.split(',')
  # Cookies as array of hashes
  all_cookies = []
  set_cookie.each do |each_cookie|
    ecookie = []
    each_cookie.strip.split(';').each do |cookie_attr|
      # replace ##### with , back
      ecookie << cookie_attr.split("=").map{|e| e.gsub(/#####/, ',') if e}
    end
    all_cookies << Hash[ecookie]
  end
  all_cookies
end