RestClient and passing cookies

35 views
Skip to first unread message

Moutalib Moutalib

unread,
Aug 12, 2014, 4:36:59 PM8/12/14
to rubyonra...@googlegroups.com
Hello,

I had this post on the Ruby channel, but maybe I have more luck here :)

I'm struggling with the last piece of the puzzle here. Basically I want
to reuse a cookie that I capture from a previous RestClient.post()
login, the only problem is that the second RestClient.post will not
accept it. I have tried different methods to pass the cookie value to
the RestClient.post(), but with no success. Also tried the base64
encoding, also failed here. Can someone please advice?

Code:
==========================================
require 'json'
require 'rest-client'

url_login = 'http://192.168.1.51/cms/v1/login/login'
url_adduser= 'http://192.168.1.51/cms/v1/config/records'

payload_login = <<-JSON
{
"login":
{
"username":"user-1",
"password":"secret",

}
}
JSON

payload_adduser= <<-JSON_ADDUSER
{
"adduser":
{
"name":"cms-users-2",
}
}
JSON_ADDUSER

initheader_login = {'Content-Type' =>
'application/x-www-form-urlencoded',:accept => :json}
initheader_add_user= {'Content-Type' => 'application/x-add-user'}

#the restexec_login goes well, I can see it login on the webserver (code
201)
restexec_login =
RestClient.post(url_login,payload_login,initheader_login)

#capture the cookie as a result of the execution of restexec_login
query_cookie = restexec_login.cookies
cookie_hash = query_cookie['SESSION_ID']
cookie = {:SESSION_ID => cookie_hash}

#the second post (below) will fail because of the missing cookie
variable
restexec_adduser=
RestClient.post(url_adduser,payload_adduser,initheader_add_user)

END CODE
==============

How can I pass the cookie in the second post method?

Thanks in advance!

Kind Regards,

iLias

--
Posted via http://www.ruby-forum.com/.

Frederick Cheung

unread,
Aug 14, 2014, 4:36:43 AM8/14/14
to rubyonra...@googlegroups.com

On Tuesday, August 12, 2014 9:36:59 PM UTC+1, Ruby-Forum.com User wrote:
#the second post (below) will fail because of the missing cookie
variable
restexec_adduser=
RestClient.post(url_adduser,payload_adduser,initheader_add_user)

END CODE
==============

How can I pass the cookie in the second post method?

 
You need to set a header of the form

    Cookie: cookie_name=cookie_value; other_cookie_name=cookie_value

if your name/value have special characters in them you'll need to quote them.

Fred

Moutalib Moutalib

unread,
Aug 16, 2014, 11:31:57 AM8/16/14
to rubyonra...@googlegroups.com
Hello Fred,

Thanks for your reply! But the problem was that the cookie was expired
before I could reuse it.

Cheers,
Reply all
Reply to author
Forward
0 new messages