using System;
using System.Collections.Generic;
using System.Net;
namespace CsharpHttpHelper.Helper
{
///
/// Cookie操作帮助类 Copyright:http://www.httphelper.com/
///
internal static class HttpCookieHelper
{
///
/// 根据字符生成Cookie和精简串,将排除path,expires,domain以及重复项
///
/// Cookie字符串
/// 精简串
internal static string GetSmallCookie(string strcookie)
{
if (string.IsNullOrWhiteSpace(strcookie))
{
return string.Empty;
}
List list = new List();
string[] array = strcookie.ToString().Split(new string[2]
{
",",
";"
}, StringSplitOptions.RemoveEmptyEntries);
string[] array2 = array;
foreach (string text in array2)
{
string text2 = text.ToLower().Trim().Replace("\r\n", string.Empty)
.Replace("\n", string.Empty);
if (!string.IsNullOrWhiteSpace(text2) && text2.Contains("=") && !text2.Contains("path=") && !text2.Contains("expires=") && !text2.Contains("domain=") && !list.Contains(text))
{
list.Add($"{text};");
}
}
return string.Join(";", list);
}
///
/// 将字符串Cookie转为CookieCollection
///
/// Cookie字符串
/// List-CookieItem
internal static CookieCollection StrCookieToCookieCollection(string strcookie)
{
if (string.IsNullOrWhiteSpace(strcookie))
{
return null;
}
CookieCollection cookieCollection = new CookieCollection();
strcookie = GetSmallCookie(strcookie);
string[] array = strcookie.ToString().Split(new string[1]
{
";"
}, StringSplitOptions.RemoveEmptyEntries);
string[] array2 = array;
foreach (string text in array2)
{
string[] array3 = text.ToString().Split(new string[1]
{
"="
}, StringSplitOptions.RemoveEmptyEntries);
if (array3.Length == 2)
{
cookieCollection.Add(new Cookie
{
Name = array3[0].Trim(),
Value = array3[1].Trim()
});
}
}
return cookieCollection;
}
///
/// 将CookieCollection转为字符串Cookie
///
/// Cookie字符串
/// strcookie
internal static string CookieCollectionToStrCookie(CookieCollection cookie)
{
if (cookie == null)
{
return string.Empty;
}
string text = string.Empty;
foreach (Cookie item in cookie)
{
text += $"{item.Name}={item.Value};";
}
return text;
}
///
/// 自动合并两个Cookie的值返回更新后结果
///
/// Cookie1
/// Cookie2
/// 返回更新后的Cookie
internal static string GetMergeCookie(string cookie1, string cookie2)
{
if (string.IsNullOrWhiteSpace(cookie1))
{
return cookie2;
}
if (string.IsNullOrWhiteSpace(cookie2))
{
return cookie1;
}
List list = new List();
string[] array = cookie1.ToString().Split(';');
string[] array2 = cookie2.ToString().Split(';');
string[] array3 = array;
foreach (string text in array3)
{
if (!list.Contains(text))
{
list.Add($"{text} ");
}
}
array3 = array2;
foreach (string text in array3)
{
if (!list.Contains(text))
{
list.Add($"{text}");
}
}
return string.Join(";", list);
}
}
}