使Ruby Net :: HTTP ::获取带有cookie的请求 [英] Making Ruby Net::HTTP::Get request with cookie

查看:53
本文介绍了使Ruby Net :: HTTP ::获取带有cookie的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过ruby打开我的stackoverflow.com页面.
而且我希望看到它就像通过身份验证一样.

I'd like to open my stackoverflow.com page via ruby.
And I'd like to see it as if I am authenticated.

我从Google Chrome浏览器中获取了 usr cookie,并创建了以下代码段:

I took 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 does output a page, but I'm not authenticated there.

是否可以在Ruby中使用Cookie发出Net :: HTTP :: Get请求?

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

推荐答案

您需要致电

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

request['Cookie'] = cookie.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


更新

作为另一个答案,结果字符串用于服务器输出.您需要删除;path = 部分.

As the other answer mentioned, the resulted string is for server output. You need to strip out ; path= part.

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

这篇关于使Ruby Net :: HTTP ::获取带有cookie的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆