我需要完成以下curl命令在Ruby中所做的事情。 curl命令登录到我的网站并存储所有返回的cookie。其中一个是会话cookie,我需要通过我的API执行进一步的休息。我如何在Ruby中做到这一点?
curl --user-agent "MyUserAgent" --cookie-jar cookiefile -o - --data 'userid=myemail%40hostname.com&passwd=mypassword' https://.../login.jsp
我目前的Ruby代码在成功登录方面起作用如下:
require 'net/http'
require 'openssl'
uri = URI.parse("https://.../login.jsp")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri)
req.set_form_data('userid' => 'myemail@hostname.com', 'passwd' => 'mypassword')
res = https.request(req)
puts res
我从“put res”到最后一行得到的是响应对象“#< Net :: HTTPFound:0x007fb6a3bd40a0>”
响应对象中的cookie是否可以通过某种方法访问它们?我不清楚我是如何得到我的饼干的。与卷曲不同,我不需要将它们放在文件中。我很乐意把它们放在哈希中,但我不知道如何访问它们。建议赞赏!!
答案 0 :(得分:0)
显然,在Ruby中实现类似cURL的行为的最佳方法是使用Curb(用于Ruby的cURL)。这是我的解决方案:
require 'curb'
def debug_handler
return ->(data_type, data) {
puts data
}
end
c =Curl::Easy.new
url = "https://some.domain.com/login.jsp"
headers={}
headers['User-Agent']='MyAgent'
creds = [Curl::PostField.content("userid","username@domain.com")]
creds << Curl::PostField.content("passwd","supersecretpassword")
c.url = url
c.headers=headers
c.enable_cookies=true
c.verbose=true
c.on_debug(&debug_handler)
c.http_post(creds)
response=c.response_code
puts response