Creating Ruby Net :: HTTP :: Get a Cookie Request

I want to open stackoverflow.com page through ruby.
And I would like to see it as if I'm authenticated.

I took the usr cookie from Google Chrome and created the following snippet:

 require 'net/http' require 'cgi' url = "http://stackoverflow.com/users/1650525/alex-smolov" uri = URI(url) http = Net::HTTP.new(uri.host, 80) request = Net::HTTP::Get.new(uri.request_uri) cookie = CGI::Cookie.new("usr", "[my cookie is here]") request['Cookie'] = cookie r = http.request(request) puts r.body 

It displays the page, but I am not authenticated there.

Is it possible to make a Net :: HTTP :: Get request in Ruby with a cookie?

+7
ruby ruby-on-rails cookies
source share
2 answers

You need to call the CGI::Cookie.to_s .

 request['Cookie'] = cookie.to_s 

Try the following code with / without .to_s .

 require 'net/http' require 'cgi' uri = URI("http://httpbin.org/cookies") http = Net::HTTP.new(uri.host, 80) request = Net::HTTP::Get.new(uri.request_uri) cookie1 = CGI::Cookie.new('usr', 'blah') request['Cookie'] = cookie1.to_s # <--- r = http.request(request) puts r.body 

UPDATE

As mentioned in another answer, the above line is for outputting the server. You need to cut ; path= ; path= part.

 CGI::Cookie.new('usr', 'value').to_s.sub(/; path=$/, '') 
+9
source

The accepted answer is incorrect. CGI::Cookie#to_s generates a string that should be sent by SERVER to the client, and not what Net :: HTTP should use. This is easy to demonstrate:

 [1] pry(main)> require 'cgi' => true [2] pry(main)> CGI::Cookie.new('usr', 'value').to_s => "usr=value; path=" 

Code like this should work better.

 require 'net/http' require 'cgi' uri = URI("http://httpbin.org/cookies") http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Get.new(uri.request_uri) request['Cookie'] = "usr=#{CGI.encode cookie_value}" r = http.request(request) puts r.body 

Or if you have multiple cookies in a hash:

 h = {'cookie1' => 'val1', 'cookie2' => 'val2'} req['Cookie'] = h.map { |k,v| "#{k}=#{CGI.encode v}" } .join('; ') 
+4
source

All Articles