[英]Making Ruby Net::HTTP::Get request with cookie
I'd like to open my stackoverflow.com page via ruby. 我想通过ruby打开我的stackoverflow.com页面。
And I'd like to see it as if I am authenticated. 而且我希望看到它好像我已经过身份验证。
I took usr
cookie from Google Chrome and created the following snippet: 我从Google Chrome中获取了
usr
cookie并创建了以下代码段:
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 does output a page, but I'm not authenticated there. 它确实输出了一个页面,但我没有在那里进行身份验证。
Is it possible to make a Net::HTTP::Get request in Ruby with cookie? 是否可以使用cookie在Ruby中创建Net :: HTTP :: Get请求?
You need to call CGI::Cookie.to_s
method. 您需要调用
CGI::Cookie.to_s
方法。
request['Cookie'] = cookie.to_s
Try following code with / without .to_s
. 尝试使用/不使用
.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 UPDATE
As the other answer mentioned, the resulted string is for server output. 正如提到的另一个答案,结果字符串用于服务器输出。 You need to strip out
; path=
你需要剥离
; path=
; path=
part. ; path=
part。
CGI::Cookie.new('usr', 'value').to_s.sub(/; path=$/, '')
The accepted answer is imho incorrect. 接受的答案是不正确的。
CGI::Cookie#to_s
generates string which should SERVER send to client, not something Net::HTTP should use. CGI::Cookie#to_s
生成应该SERVER发送给客户端的字符串,而不是Net :: HTTP应该使用的字符串。 It can be easily demonstrated: 它可以很容易地证明:
[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 in case you have multiple cookies in a hash: 或者,如果您在哈希中有多个cookie:
h = {'cookie1' => 'val1', 'cookie2' => 'val2'}
req['Cookie'] = h.map { |k,v| "#{k}=#{CGI.encode v}" } .join('; ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.