2011-04-28 84 views
1

我现在已经有了这段代码来找出URL的重定向路径。 问题是我无法通过任何cookie。将Cookie传递给Net :: HTTP.start

任何人都知道该怎么做?

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 

回答

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