Jasmine Lognnes
Jasmine Lognnes

Reputation: 7097

How to parse cookies in HTTPClient?

In the below script I access a website which does many redirects and I need to know the URL/port of the last redirect.

cookie_file = Tempfile.new('cookie_jar.txt')
client.set_cookie_store(cookie_file)
client.set_auth(nil, user, pass)
client.ssl_config.verify_mode = nil

r = client.get(uri, :follow_redirect => true)
r = client.get_content(uri, :follow_redirect => true)

pp client.cookie_manager.jar

Looking at the cookies I can see from the second cookie that this time is was https://example.com:65003. If I try again then it will be a different port.

Question

How can I parse a HTTPClient cookie?

[#<HTTP::Cookie:name="ASPSESSIONIDQGDSCTSA",
value="DBEHBGICIKNNIBBMNAMGIMFG", domain="example.com",
for_domain=false, path="/", secure=true, httponly=false, expires=nil,
max_age=nil, created_at=2017-04-12 20:09:58 +0200,
accessed_at=2017-04-12 20:09:58 +0200 
origin=https://example.com/bwtem/?follow_redirect=true>,

#<HTTP::Cookie:name="ASPSESSIONIDSGAQARRD",
value="APJDHADDOHENHCCHOLLMAHNJ", domain="example.com",
for_domain=false, path="/", secure=true, httponly=false, expires=nil,
max_age=nil, created_at=2017-04-12 20:09:57 +0200,
accessed_at=2017-04-12 20:09:58 +0200 
origin=https://example.com:9000/auth/?id=7C05C91D24C4A798230A29FD28C587F3&target=https://example.com:65003&>]

Upvotes: 1

Views: 311

Answers (1)

Anthony
Anthony

Reputation: 15967

You can do it with the URI module:

origin
=> "https://example.com:9000/auth/?id=7C05C91D24C4A798230A29FD28C587F3&target=https://example.com:65003&"
URI.decode_www_form(URI.parse(origin).query).to_h["target"]
=> "https://example.com:65003"

Upvotes: 1

Related Questions