Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby HTTP post with session cookie

I'm trying to write a Ruby script to use the API on the image gallery site Piwigo, this requires you to login first with one HTTP post and upload an image with another post.

This is what I've got so far but it doesn't work, just returns a 401 error, can anyone see where I am going wrong?

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

Which gives this response when run;

$ ruby piwigo.rb
401
Unauthorized

There is a Perl example on their API page which I was trying to convert to Ruby http://piwigo.org/doc/doku.php?id=dev:webapi:pwg.images.addsimple

like image 923
Alastair Montgomery Avatar asked Nov 12 '22 05:11

Alastair Montgomery


1 Answers

By using the nice_http gem: https://github.com/MarioRuiz/nice_http NiceHttp will take care of your cookies so you don't have to do anything

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

Also if you want you can add your own cookies by using http.cookies

like image 71
Mario Ruiz Avatar answered Nov 15 '22 04:11

Mario Ruiz