带有会话cookie的Ruby HTTP帖子

Ala*_*ery 5 ruby cookies post http

我正在尝试编写一个Ruby脚本来使用图像库网站Piwigo上的API,这要求您首先使用一个HTTP帖子登录并使用另一个帖子上传图像.

这是我到目前为止所做的,但它不起作用,只返回401错误,任何人都可以看到我错在哪里?

require 'net/http'
require 'pp'

http = Net::HTTP.new('mydomain.com',80)
path = '/piwigo/ws.php'
data = 'method=pwg.session.login&username=admin&password=password'
resp, data = http.post(path, data, {})
if (resp.code == '200')
    cookie = resp.response['set-cookie']
    data = 'method=pwg.images.addSimple&image=image.jpg&category=7'
    headers = { "Cookie" => cookie }
    resp, data = http.post(path, data, headers)
    puts resp.code
    puts resp.message
end
Run Code Online (Sandbox Code Playgroud)

运行时会给出此响应;

$ ruby piwigo.rb
401
Unauthorized
Run Code Online (Sandbox Code Playgroud)

他们的API页面上有一个Perl示例,我试图将其转换为Ruby http://piwigo.org/doc/doku.php?id=dev:webapi:pwg.images.addsimple

Mar*_*uiz 2

通过使用 Nice_http gem:https://github.com/MarioRuiz/nice_http NiceHttp 将处理您的 cookie,因此您无需执行任何操作

require 'nice_http'
path = '/piwigo/ws.php'
data = '?method=pwg.session.login&username=admin&password=password'

http = NiceHttp.new('http://example.com')
resp = http.get(path+data)

if resp.code == 200
    resp = http.post(path)
    puts resp.code
    puts resp.message
end
Run Code Online (Sandbox Code Playgroud)

另外,如果您愿意,您可以使用 http.cookies 添加您自己的 cookie