How to implement cookie support in ruby net/http?

后端 未结 6 1071
闹比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 10:58

    Taken from DZone Snippets

    http = Net::HTTP.new('profil.wp.pl', 443)
    http.use_ssl = true
    path = '/login.html'
    
    # GET request -> so the host can set his cookies
    resp, data = http.get(path, nil)
    cookie = resp.response['set-cookie'].split('; ')[0]
    
    
    # POST request -> logging in
    data = 'serwis=wp.pl&url=profil.html&tryLogin=1&countTest=1&logowaniessl=1&login_username=blah&login_password=blah'
    headers = {
      'Cookie' => cookie,
      'Referer' => 'http://profil.wp.pl/login.html',
      'Content-Type' => 'application/x-www-form-urlencoded'
    }
    
    resp, data = http.post(path, data, headers)
    
    
    # Output on the screen -> we should get either a 302 redirect (after a successful login) or an error page
    puts 'Code = ' + resp.code
    puts 'Message = ' + resp.message
    resp.each {|key, val| puts key + ' = ' + val}
    puts data
    

    update

    #To save the cookies, you can use PStore
    cookies = PStore.new("cookies.pstore")
    
    # Save the cookie  
    cookies.transaction do
      cookies[:some_identifier] = cookie
    end
    
    # Retrieve the cookie back
    cookies.transaction do
      cookie = cookies[:some_identifier] 
    end
    

提交回复
热议问题