小网站中我们curl模拟登陆可能只需要保存一个登陆成功的Cookies就等请求全站权限,但是对于大网站则不可以,不同接口生成的cookies可能不同。
最新在编写微信网页版winform请求。需要将登陆的cookies更新内容特别整理。
代码语言:javascript复制//精简Cookie将自动去掉rn换行符号,path,expires,domain,去重复等多余选项
internal static string GetSmallCookie(string strcookie)
{
string result;
if (string.IsNullOrWhiteSpace(strcookie))
{
result = string.Empty;
}
else
{
List<string> list = new List<string>();
string[] array = strcookie.ToString().Split(new string[]
{
",",
";"
}, StringSplitOptions.RemoveEmptyEntries);
string[] array2 = array;
for (int i = 0; i < array2.Length; i )
{
string text = array2[i];
string text2 = text.ToLower().Trim().Replace("rn", string.Empty).Replace("n", string.Empty);
if (!string.IsNullOrWhiteSpace(text2))
{
if (text2.Contains("="))
{
if (!text2.Contains("path="))
{
if (!text2.Contains("expires="))
{
if (!text2.Contains("domain="))
{
if (!list.Contains(text))
{
list.Add(string.Format("{0};", text));
}
}
}
}
}
}
}
result = string.Join(";", list);
}
return result;
}
代码语言:javascript复制//合并Cookie的方法,参数请先使用GetSmallCookie()过滤后使用
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)
{
//Console.WriteLine("cookie:" cookie);
if (!string.IsNullOrWhiteSpace(cookie))
{
if (!string.IsNullOrWhiteSpace(cookie.Split('=')[1])) //判断cookie的value值是为空,不为空时才进行操作
{
bool isFind = false; //判断是否是新值
for (int i = 0; i < oldcookielist.Count; i )
{
if (cookie.Split('=')[0] == oldcookielist[i].Split('=')[0])
{
//oldcookielist[i].Split('=')[1] = cookie.Split('=')[1];
oldcookielist[i] = cookie;
isFind = true;
break;
}
}
if (!isFind) //如果计算后还是false,则表示newcookie里出现新值了,将新值添加到老cookie里
oldcookielist.Add(cookie);
}
}
}
oldcookie = string.Empty;
for (int i = 0; i < oldcookielist.Count; i )
oldcookie = oldcookielist[i] ";";
return oldcookie;
}