【问题标题】:Ruby HTTP post with session cookie带有会话 cookie 的 Ruby HTTP 发布
【发布时间】:2019-01-02 23:47:10
【问题描述】:

我正在尝试编写一个 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

运行时会给出这个响应;

$ ruby piwigo.rb
401
Unauthorized

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

【问题讨论】:

    标签: ruby http post cookies


    【解决方案1】:

    通过使用 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
    

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

    【讨论】:

      【解决方案2】:

      您可以使用名为 mechanize 的 gem。它透明地处理 cookie。

      【讨论】:

      • 谢谢,我去看看,我认为驱动网页比访问 Web API 更多?
      猜你喜欢
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 2015-02-09
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      相关资源
      最近更新 更多