0

通过我的代码,我通过获取请求获取 cookie:

http = Net::HTTP.new('kdfgdfgdfglat.gsdfsdo', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = '/gfgdfgdfgfdgdfg'
resp, data = http.get(path, {'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0', "Cookie" => "dfgdfgdfg=17"})

cookie = resp.response['set-cookie']

饼干是这样的:

ASP.NET_SessionId=mnxjnm140qvvt4wvlfielud3; domain=.e-dfgdfgdfg.godfgdfgv.pl; path=/; secure; HttpOnly, TSe20548=a4ad9705817edcebbdf2e0c3f869b10843e5bb63617303a3523b64a0; Path=/, TS7848cb=98330ff418e3c9a3b2afb5f10398363043e5bb63617303a3523b64a036af3f5e7cfaddf8; path=/; domain=.e-dfgfdgdfgf.godfgdfggv.pdfgdfl, TSe20548_31=88ba62b4efd7e40ff9fa891b1764eb6e43e5bb63617303a3000000000000000000e1d4e1bdb727a5ac9c00848b7c7c770a3b491a57; Path=/ 

但如您所见,我有 ASP.NET_SessionId、TSe20548_31 等(20548 也是动态的,数字可能是其他的)。

我的问题是如何清除和格式化cookies,这样的观点:

ASP.NET_SessionId=mnxjnm140qvvt4wvlfielud3; TSe20548=a4ad9705817edcebbdf2e0c3f869b10843e5bb63617303a3523b64a0; TS7848cb=98330ff418e3c9a3b2afb5f10398363043e5bb63617303a3523b64a036af3f5e7cfaddf8; TSe20548_31=88ba62b4efd7e40ff9fa891b1764eb6e43e5bb63617303a3000000000000000000e1d4e1bdb727a5ac9c00848b7c7c770a3b491a57;

如您所见,我必须只获取 cookie 及其值,没有路径和其他额外信息。我怎么能这样做?这是真的吗?如何从cookie中删除一些数据?所以我需要留下 ASP.NET_SessionId 和它的值,以及 TS*** 和那些值。我该怎么做?

4

1 回答 1

1

这真的没那么难。只需拆分分号并过滤即可。或扫描字符串以查找您感兴趣的配对。像这样的东西:

s1 = "ASP.NET_SessionId=mnxjnm140qvvt4wvlfielud3; domain=.e-konsulat.gov.pl; path=/; secure; HttpOnly, TSe20548=a4ad9705817edcebbdf2e0c3f869b10843e5bb63617303a3523b64a0; Path=/, TS7848cb=98330ff418e3c9a3b2afb5f10398363043e5bb63617303a3523b64a036af3f5e7cfaddf8; path=/; domain=.e-konsulat.gov.pl, TSe20548_31=88ba62b4efd7e40ff9fa891b1764eb6e43e5bb63617303a3000000000000000000e1d4e1bdb727a5ac9c00848b7c7c770a3b491a57; Path=/ "

regex = /(?<key>(ASP\.NET_SessionId|TS\w+)=[^;]+)/

a1 = s1.scan(regex).flatten # => ["ASP.NET_SessionId=mnxjnm140qvvt4wvlfielud3", "TSe20548=a4ad9705817edcebbdf2e0c3f869b10843e5bb63617303a3523b64a0", "TS7848cb=98330ff418e3c9a3b2afb5f10398363043e5bb63617303a3523b64a036af3f5e7cfaddf8", "TSe20548_31=88ba62b4efd7e40ff9fa891b1764eb6e43e5bb63617303a3000000000000000000e1d4e1bdb727a5ac9c00848b7c7c770a3b491a57"]
a2 = a1.map{|s| s.split('=')} # => [["ASP.NET_SessionId", "mnxjnm140qvvt4wvlfielud3"], ["TSe20548", "a4ad9705817edcebbdf2e0c3f869b10843e5bb63617303a3523b64a0"], ["TS7848cb", "98330ff418e3c9a3b2afb5f10398363043e5bb63617303a3523b64a036af3f5e7cfaddf8"], ["TSe20548_31", "88ba62b4efd7e40ff9fa891b1764eb6e43e5bb63617303a3000000000000000000e1d4e1bdb727a5ac9c00848b7c7c770a3b491a57"]]
h1 = Hash[a2] # => {"ASP.NET_SessionId"=>"mnxjnm140qvvt4wvlfielud3", "TSe20548"=>"a4ad9705817edcebbdf2e0c3f869b10843e5bb63617303a3523b64a0", "TS7848cb"=>"98330ff418e3c9a3b2afb5f10398363043e5bb63617303a3523b64a036af3f5e7cfaddf8", "TSe20548_31"=>"88ba62b4efd7e40ff9fa891b1764eb6e43e5bb63617303a3000000000000000000e1d4e1bdb727a5ac9c00848b7c7c770a3b491a57"}
于 2013-09-20T13:21:00.550 回答