How to implement cookie support in ruby net/http?

后端 未结 6 1038
闹比i
闹比i 2020-12-07 10:43

I\'d like to add cookie support to a ruby class utilizing net/http to browse the web. Cookies have to be stored in a file to survive after the script has ended. Of course I

6条回答
  •  一生所求
    2020-12-07 11:18

    The accepted answer will not work if your server returns and expects multiple cookies. This could happen, for example, if the server returns a set of FedAuth[n] cookies. If this affects you, you might want to look into using something along the lines of the following instead:

    http = Net::HTTP.new('https://example.com', 443)
    http.use_ssl = true
    path1 = '/index.html'
    path2 = '/index2.html'
    
    # make a request to get the server's cookies
    response = http.get(path)
    if (response.code == '200')
        all_cookies = response.get_fields('set-cookie')
        cookies_array = Array.new
        all_cookies.each { | cookie |
            cookies_array.push(cookie.split('; ')[0])
        }
        cookies = cookies_array.join('; ')
    
        # now make a request using the cookies
        response = http.get(path2, { 'Cookie' => cookies })
    end
    

提交回复
热议问题