Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement cookie support in ruby net/http?

Tags:

ruby

cookies

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 can read the specs and write some kind of a handler, use some cookie.txt format and so on, but it seems to mean reinventing the wheel. Is there a better way to accomplish this task? Maybe some kind of a cooie jar class to take care of cookies?

like image 766
Fluffy Avatar asked Sep 28 '09 12:09

Fluffy


People also ask

How do I add cookies to my HTTP request?

To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.

How is a cookie represented in an HTTP request and an HTTP response?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

Is Cookie in HTTP header?

A cookie is an HTTP request header i.e. used in the requests sent by the user to the server. It contains the cookies previously sent by the server using set-cookies. It is an optional header.

Can we set cookie in post request?

No. fetch and XHR both let you tell the browser to send any cookies it has stored for the URL in the request, but this question is about manually adding a cookie with JavaScript.


1 Answers

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 
like image 139
mamills Avatar answered Sep 28 '22 02:09

mamills