开发者

Pass cookie to Net::HTTP.start

I've this code right now to figure out the redirect path for a url. The problem is that I can't pass any cookies.

Anyone knows how to do that?

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['lo开发者_如何学编程cation'] ? url = URI.parse(res.header['location']) : 
found = true 
end


Here is the solution.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜