将cookie传递给Net :: HTTP.start

时间:2011-04-28 21:33:14

标签: ruby

我现在正在使用此代码来确定网址的重定向路径。 问题是我无法传递任何cookie。

任何人都知道如何做到这一点?

url = URI.parse("http://example.com") # Make sure you put the trailing slash on! 

found = false 
until found 
  host, port = url.host, url.port if url.host && url.port 
  req = Net::HTTP::Get.new(url.path)

  res = Net::HTTP.start(url.host, url.port) do |http| 
    http.request(req)
  end
  puts res.header['location']
  res.header['location'] ? url = URI.parse(res.header['location']) : 
found = true 
end

1 个答案:

答案 0 :(得分:4)

这是解决方案。

url = URI.parse("http://example.com")

found = false 
until found 
  host, port = url.host, url.port if url.host && url.port 
  req = Net::HTTP::Get.new(url.path, {
    "Cookie" => "sessid=123;"
  })

  res = Net::HTTP.start(url.host, url.port) do |http| 
    http.request(req)
  end
  puts res.header['location']
  res.header['location'] ? url = URI.parse(res.header['location']) : found = true 
end