2011-04-28 81 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