在连续的get请求中保留会话/ cookie

时间:2016-08-08 12:41:20

标签: cookies get rest-client

我正在运行一个脚本,需要使用RestClient gem对API执行几个GET请求。

但是,此API需要Cookie和要保持会话以便正常运行。

我有这个:

# first request
url = "http://example-api.com/first-endpoint?param1=foo&param2=bar
request = RestClient.get url, :content_type => :json, :accept => :json
cookies = request.cookies

# second request
url = "http://example-api.com/second-endpoint?param1=foo&param2=bar
request = RestClient.get url, :content_type => :json, :accept => :json

为了使第二个请求有效,我需要保持相同的会话和cookie。使用RestClient,我可以在POST请求中发回cookie,如下所示:

RestClient.post post_url, {}, {:cookies => cookies}

但我无法在他们的文档和文件中找到在StackOverFlow上以任何方式为GET请求执行此操作。

我应该如何继续"保持"两个连续的GET请求之间存在的cookie?如果RestClient不支持,我也可以使用其他宝石或技术。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

请注意,如果您想要更完全成熟的Cookie支持,在最新版本的rest-client(> = 2.0.0)中,您可以使用实际的Cookie jar(HTTP::CookieJar),其行为更像是浏览器在以下过期/域/路径限制。

resp = RestClient.get(url)
jar = resp.cookie_jar

resp2 = RestClient::Request.execute(url: someurl, method: :get, cookies: jar)

答案 1 :(得分:0)

我试过了:

RestClient.get url,{:cookies => cookies}

似乎工作正常!