开发中经常遇到cookies更新的方法,以下方法为传入旧cookies和新cookies,自动合并更新为新的cookies,旧cookies和新cookies中的相同参数将会被新cookies的值给覆盖。
public static string updateCookie(string oldcookie, string newcookie) { List<string> oldcookielist = new List<string>(); if (oldcookie.Contains(";")) oldcookielist = new List<string>(oldcookie.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)); else oldcookielist.Add(oldcookie); List<string> newcookielist = new List<string>(); if (newcookie.Contains(";")) newcookielist = new List<string>(newcookie.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)); else newcookielist.Add(newcookie); foreach (string cookie in newcookielist) { if (!string.IsNullOrWhiteSpace(cookie)) { if (!string.IsNullOrWhiteSpace(cookie.Split('=')[1])) { bool isFind = false; for (int i = 0; i < oldcookielist.Count; i++) { if (cookie.Split('=')[0] == oldcookielist[i].Split('=')[0]) { oldcookielist[i] = cookie; isFind = true; break; } } if (!isFind) oldcookielist.Add(cookie); } } } oldcookie = string.Empty; for (int i = 0; i < oldcookielist.Count; i++) oldcookie += oldcookielist[i] + ";"; return oldcookie; }
评论前必须登录!
注册