2064 lines
78 KiB
C#
2064 lines
78 KiB
C#
|
||
using CsharpHttpHelper.Down;
|
||
using CsharpHttpHelper.Properties;
|
||
using System;
|
||
using System.CodeDom.Compiler;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using System.Diagnostics;
|
||
using System.Drawing;
|
||
using System.Drawing.Imaging;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Reflection;
|
||
using System.Runtime.CompilerServices;
|
||
using System.Runtime.InteropServices;
|
||
using System.Runtime.Serialization.Formatters.Binary;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Text.RegularExpressions;
|
||
using System.Threading;
|
||
using System.Web;
|
||
using System.Xml;
|
||
|
||
namespace CsharpHttpHelper
|
||
{
|
||
public class AESCryption
|
||
{
|
||
/// <summary>
|
||
/// AES 加密
|
||
/// </summary>
|
||
/// <param name="str">明文(待加密)</param>
|
||
/// <param name="key">密文</param>
|
||
/// <returns></returns>
|
||
public string AesEncrypt(string str, string key)
|
||
{
|
||
return AesEncrypt(str, Encoding.UTF8.GetBytes(key));
|
||
}
|
||
|
||
/// <summary>
|
||
/// AES 加密
|
||
/// </summary>
|
||
/// <param name="str">明文(待加密)</param>
|
||
/// <param name="key">密文</param>
|
||
/// <returns></returns>
|
||
public string AesEncrypt(string str, byte[] key)
|
||
{
|
||
if (string.IsNullOrEmpty(str)) return null;
|
||
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
|
||
RijndaelManaged rm = new RijndaelManaged
|
||
{
|
||
Key = key,
|
||
Mode = CipherMode.ECB,
|
||
Padding = PaddingMode.PKCS7
|
||
};
|
||
;
|
||
ICryptoTransform cTransform = rm.CreateEncryptor();
|
||
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
||
|
||
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
|
||
}
|
||
|
||
|
||
|
||
#region 将Base64编码的文本转换成普通文本
|
||
/// <summary>
|
||
/// 将Base64编码的文本转换成普通文本
|
||
/// </summary>
|
||
/// <param name="base64">Base64编码的文本</param>
|
||
/// <returns></returns>
|
||
public static string Base64StringToString(string base64)
|
||
{
|
||
if (base64 != "")
|
||
{
|
||
char[] charBuffer = base64.ToCharArray();
|
||
byte[] bytes = System.Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
|
||
string returnstr = Encoding.Default.GetString(bytes);
|
||
return returnstr;
|
||
}
|
||
else
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
#endregion
|
||
#region 字符串转为base64字符串
|
||
public static string StringToBase64String(string str)
|
||
{
|
||
if (str != "" && str != null)
|
||
{
|
||
byte[] b = Encoding.Default.GetBytes(str);
|
||
string returnstr = System.Convert.ToBase64String(b);
|
||
return returnstr;
|
||
}
|
||
else
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
#endregion
|
||
/// <summary>
|
||
/// AES 解密
|
||
/// </summary>
|
||
/// <param name="str">明文(待解密)</param>
|
||
/// <param name="key">密文</param>
|
||
/// <returns></returns>
|
||
public string AesDecrypt(string str, string key)
|
||
{
|
||
return AesDecrypt(str, Encoding.UTF8.GetBytes(key));
|
||
}
|
||
|
||
public string AesDecrypt(string str, byte[] key)
|
||
{
|
||
if (string.IsNullOrEmpty(str)) return null;
|
||
Byte[] toEncryptArray = Convert.FromBase64String(str);
|
||
|
||
RijndaelManaged rm = new RijndaelManaged
|
||
{
|
||
Key = key,
|
||
Mode = CipherMode.ECB,
|
||
Padding = PaddingMode.PKCS7
|
||
};
|
||
|
||
ICryptoTransform cTransform = rm.CreateDecryptor();
|
||
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
|
||
|
||
return Encoding.UTF8.GetString(resultArray);
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// WinInet的方式请求数据
|
||
/// </summary>
|
||
public class Wininet
|
||
{
|
||
#region WininetAPI
|
||
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
|
||
private static extern int InternetOpen(string strAppName, int ulAccessType, string strProxy, string strProxyBypass, int ulFlags);
|
||
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
|
||
private static extern int InternetConnect(int ulSession, string strServer, int ulPort, string strUser, string strPassword, int ulService, int ulFlags, int ulContext);
|
||
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
|
||
private static extern bool InternetCloseHandle(int ulSession);
|
||
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
|
||
private static extern bool HttpAddRequestHeaders(int hRequest, string szHeasers, uint headersLen, uint modifiers);
|
||
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
|
||
private static extern int HttpOpenRequest(int hConnect, string szVerb, string szURI, string szHttpVersion, string szReferer, string accetpType, int dwflags, int dwcontext);
|
||
[DllImport("wininet.dll")]
|
||
private static extern bool HttpSendRequestA(int hRequest, string szHeaders, int headersLen, string options, int optionsLen);
|
||
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
|
||
private static extern bool InternetReadFile(int hRequest, byte[] pByte, int size, out int revSize);
|
||
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||
private static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved);
|
||
#endregion
|
||
|
||
#region 重载方法
|
||
/// <summary>
|
||
/// WinInet 方式GET
|
||
/// </summary>
|
||
/// <param name="Url">地址</param>
|
||
/// <returns></returns>
|
||
public string GetData(string Url)
|
||
{
|
||
using (MemoryStream ms = GetHtml(Url, ""))
|
||
{
|
||
if (ms != null)
|
||
{
|
||
//无视编码
|
||
Match meta = Regex.Match(Encoding.Default.GetString(ms.ToArray()), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
|
||
string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToUpper().Trim() : string.Empty;
|
||
if (c.Length > 2)
|
||
{
|
||
if (c.IndexOf("UTF-8") != -1)
|
||
{
|
||
return Encoding.GetEncoding("UTF-8").GetString(ms.ToArray());
|
||
}
|
||
}
|
||
return Encoding.GetEncoding("GBK").GetString(ms.ToArray());
|
||
}
|
||
else
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// POST
|
||
/// </summary>
|
||
/// <param name="Url">地址</param>
|
||
/// <param name="postData">提交数据</param>
|
||
/// <returns></returns>
|
||
public string PostData(string Url, string postData)
|
||
{
|
||
using (MemoryStream ms = GetHtml(Url, postData))
|
||
{
|
||
//无视编码
|
||
Match meta = Regex.Match(Encoding.Default.GetString(ms.ToArray()), "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase);
|
||
string c = (meta.Groups.Count > 1) ? meta.Groups[2].Value.ToUpper().Trim() : string.Empty;
|
||
if (c.Length > 2)
|
||
{
|
||
if (c.IndexOf("UTF-8") != -1)
|
||
{
|
||
return Encoding.GetEncoding("UTF-8").GetString(ms.ToArray());
|
||
}
|
||
}
|
||
return Encoding.GetEncoding("GBK").GetString(ms.ToArray());
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// GET(UTF-8)模式
|
||
/// </summary>
|
||
/// <param name="Url">地址</param>
|
||
/// <returns></returns>
|
||
public string GetUtf8(string Url)
|
||
{
|
||
using (MemoryStream ms = GetHtml(Url, ""))
|
||
{
|
||
return Encoding.GetEncoding("UTF-8").GetString(ms.ToArray());
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// POST(UTF-8)
|
||
/// </summary>
|
||
/// <param name="Url">地址</param>
|
||
/// <param name="postData">提交数据</param>
|
||
/// <returns></returns>
|
||
public string PostUtf8(string Url, string postData)
|
||
{
|
||
using (MemoryStream ms = GetHtml(Url, postData))
|
||
{
|
||
return Encoding.GetEncoding("UTF-8").GetString(ms.ToArray());
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 获取网页图片(Image)
|
||
/// </summary>
|
||
/// <param name="Url">图片地址</param>
|
||
/// <returns></returns>
|
||
public Image GetImage(string Url)
|
||
{
|
||
using (MemoryStream ms = GetHtml(Url, ""))
|
||
{
|
||
if (ms == null)
|
||
{
|
||
return null;
|
||
}
|
||
Image img = Image.FromStream(ms);
|
||
return img;
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 方法
|
||
/// <summary>
|
||
/// 请求数据
|
||
/// </summary>
|
||
/// <param name="Url">请求地址</param>
|
||
/// <param name="Postdata">提交的数据</param>
|
||
/// <param name="Header">请求头</param>
|
||
/// <returns></returns>
|
||
private MemoryStream GetHtml(string Url, string Postdata, StringBuilder Header = null)
|
||
{
|
||
try
|
||
{
|
||
//声明部分变量
|
||
Uri uri = new Uri(Url);
|
||
string Method = "GET";
|
||
if (Postdata != "")
|
||
{
|
||
Method = "POST";
|
||
}
|
||
string UserAgent = "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; 125LA; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
|
||
int hSession = InternetOpen(UserAgent, 1, "", "", 0);//会话句柄
|
||
if (hSession == 0)
|
||
{
|
||
InternetCloseHandle(hSession);
|
||
return null;//Internet句柄获取失败则返回
|
||
}
|
||
int hConnect = InternetConnect(hSession, uri.Host, uri.Port, "", "", 3, 0, 0);//连接句柄
|
||
if (hConnect == 0)
|
||
{
|
||
InternetCloseHandle(hConnect);
|
||
InternetCloseHandle(hSession);
|
||
return null;//Internet连接句柄获取失败则返回
|
||
}
|
||
//请求标记
|
||
int gettype = -2147483632;
|
||
if (Url.Substring(0, 5) == "https")
|
||
{
|
||
gettype = -2139095024;
|
||
}
|
||
else
|
||
{
|
||
gettype = -2147467248;
|
||
}
|
||
//取HTTP请求句柄
|
||
int hRequest = HttpOpenRequest(hConnect, Method, uri.PathAndQuery, "HTTP/1.1", "", "", gettype, 0);//请求句柄
|
||
if (hRequest == 0)
|
||
{
|
||
InternetCloseHandle(hRequest);
|
||
InternetCloseHandle(hConnect);
|
||
InternetCloseHandle(hSession);
|
||
return null;//HTTP请求句柄获取失败则返回
|
||
}
|
||
//添加HTTP头
|
||
StringBuilder sb = new StringBuilder();
|
||
if (Header == null)
|
||
{
|
||
sb.Append("Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n");
|
||
sb.Append("Content-Type:application/x-www-form-urlencoded\r\n");
|
||
sb.Append("Accept-Language:zh-cn\r\n");
|
||
sb.Append("Referer:" + Url);
|
||
}
|
||
else
|
||
{
|
||
sb = Header;
|
||
}
|
||
//获取返回数据
|
||
if (string.Equals(Method, "GET", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
HttpSendRequestA(hRequest, sb.ToString(), sb.Length, "", 0);
|
||
}
|
||
else
|
||
{
|
||
HttpSendRequestA(hRequest, sb.ToString(), sb.Length, Postdata, Postdata.Length);
|
||
}
|
||
//处理返回数据
|
||
int revSize = 0;//计次
|
||
byte[] bytes = new byte[1024];
|
||
MemoryStream ms = new MemoryStream();
|
||
while (true)
|
||
{
|
||
bool readResult = InternetReadFile(hRequest, bytes, 1024, out revSize);
|
||
if (readResult && revSize > 0)
|
||
{
|
||
ms.Write(bytes, 0, revSize);
|
||
}
|
||
else
|
||
{
|
||
break;
|
||
}
|
||
}
|
||
InternetCloseHandle(hRequest);
|
||
InternetCloseHandle(hConnect);
|
||
InternetCloseHandle(hSession);
|
||
return ms;
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region 获取webbrowser的cookies
|
||
/// <summary>
|
||
/// 取出cookies
|
||
/// </summary>
|
||
/// <param name="url">完整的链接格式</param>
|
||
/// <returns></returns>
|
||
public string GetCookies(string url)
|
||
{
|
||
uint datasize = 256;
|
||
StringBuilder cookieData = new StringBuilder((int)datasize);
|
||
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero))
|
||
{
|
||
if (datasize < 0)
|
||
return null;
|
||
|
||
cookieData = new StringBuilder((int)datasize);
|
||
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero))
|
||
return null;
|
||
}
|
||
return cookieData.ToString() + ";";
|
||
}
|
||
#endregion
|
||
|
||
#region String与CookieContainer互转
|
||
/// <summary>
|
||
/// 遍历CookieContainer
|
||
/// </summary>
|
||
/// <param name="cc"></param>
|
||
/// <returns></returns>
|
||
public List<Cookie> GetAllCookies(CookieContainer cc)
|
||
{
|
||
List<Cookie> lstCookies = new List<Cookie>();
|
||
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
|
||
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
|
||
System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
|
||
|
||
foreach (object pathList in table.Values)
|
||
{
|
||
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
|
||
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
|
||
| System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
|
||
foreach (CookieCollection colCookies in lstCookieCol.Values)
|
||
foreach (Cookie c in colCookies) lstCookies.Add(c);
|
||
}
|
||
return lstCookies;
|
||
|
||
}
|
||
/// <summary>
|
||
/// 将String转CookieContainer
|
||
/// </summary>
|
||
/// <param name="url"></param>
|
||
/// <param name="cookie"></param>
|
||
/// <returns></returns>
|
||
public CookieContainer StringToCookie(string url, string cookie)
|
||
{
|
||
string[] arrCookie = cookie.Split(';');
|
||
CookieContainer cookie_container = new CookieContainer(); //加载Cookie
|
||
try
|
||
{
|
||
foreach (string sCookie in arrCookie)
|
||
{
|
||
if (sCookie.IndexOf("expires") > 0)
|
||
continue;
|
||
cookie_container.SetCookies(new Uri(url), sCookie);
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
foreach (string sCookie in arrCookie)
|
||
{
|
||
Cookie ck = new Cookie();
|
||
ck.Name = sCookie.Split('=')[0].Trim();
|
||
ck.Value = sCookie.Split('=')[1].Trim();
|
||
ck.Domain = url;
|
||
cookie_container.Add(ck);
|
||
}
|
||
|
||
}
|
||
return cookie_container;
|
||
}
|
||
/// <summary>
|
||
/// 将CookieContainer转换为string类型
|
||
/// </summary>
|
||
/// <param name="cc"></param>
|
||
/// <returns></returns>
|
||
public string CookieToString(CookieContainer cc)
|
||
{
|
||
System.Collections.Generic.List<Cookie> lstCookies = new System.Collections.Generic.List<Cookie>();
|
||
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
|
||
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
|
||
System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
|
||
StringBuilder sb = new StringBuilder();
|
||
foreach (object pathList in table.Values)
|
||
{
|
||
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
|
||
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
|
||
| System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
|
||
foreach (CookieCollection colCookies in lstCookieCol.Values)
|
||
foreach (Cookie c in colCookies)
|
||
{
|
||
sb.Append(c.Name).Append("=").Append(c.Value).Append(";");
|
||
}
|
||
}
|
||
return sb.ToString();
|
||
}
|
||
#endregion
|
||
}
|
||
|
||
public static class HttpExtend
|
||
{
|
||
/// <summary>
|
||
/// 正则获取Url链接
|
||
/// </summary>
|
||
public const string REGEX_GETURL = @"(?<链接>(?:(?:ht|f)tps?):\/\/[\w\-]+(?:\.[\w\-]+)+(?:[A-Za-z0-9_\-\.,@?^=%&:\/~\+#]*[A-Za-z0-9_\-\.,@?^=%&:\/~\+#])?)";
|
||
|
||
/// <summary>
|
||
/// 匹配单条url
|
||
/// </summary>
|
||
/// <param name="content"></param>
|
||
/// <returns></returns>
|
||
public static string RegexMatchUrl(string content)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(content))
|
||
return content;
|
||
var reg = Regex.Match(content.Replace("&", "&"), REGEX_GETURL, RegexOptions.IgnoreCase);
|
||
if (reg.Success)
|
||
return reg.Groups["链接"].Value.Replace(@"\/", "/").Trim();
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 自定义正则字符串,只匹配第一个
|
||
/// </summary>
|
||
/// <param name="content"></param>
|
||
/// <param name="regexStr"></param>
|
||
/// <returns></returns>
|
||
public static string RegexMatch(string content, string regexStr)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(content))
|
||
return content;
|
||
var reg = Regex.Match(content, regexStr, RegexOptions.IgnoreCase);
|
||
if (reg.Success)
|
||
return reg.Groups[1].Value;
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 多条url匹配
|
||
/// </summary>
|
||
/// <param name="content"></param>
|
||
/// <returns></returns>
|
||
public static List<string> RegexMatchesUrl(string content)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(content))
|
||
{
|
||
var regs = Regex.Matches(content.Replace("$amp;", "$"), REGEX_GETURL, RegexOptions.IgnoreCase | RegexOptions.Multiline);
|
||
if (regs != null && regs.Count != 0)
|
||
{
|
||
List<string> list = new List<string>();
|
||
foreach (Match reg in regs)
|
||
{
|
||
list.Add(reg.Groups["链接"].Value.Replace(@"\/", "/").Trim());
|
||
}
|
||
return list;
|
||
}
|
||
}
|
||
return new List<string>();
|
||
}
|
||
|
||
public static T ConvertEnum<T>(string value)
|
||
{
|
||
var v = System.Enum.Parse(typeof(T), value);
|
||
return (T)v;
|
||
}
|
||
public static T ConvertEnum<T>(int value)
|
||
{
|
||
return (T)System.Enum.Parse(typeof(T), value.ToString());
|
||
}
|
||
public static T ConvertEnum<T>(ushort value)
|
||
{
|
||
return (T)System.Enum.Parse(typeof(T), value.ToString());
|
||
}
|
||
|
||
#region 是否base64字符串
|
||
|
||
private static char[] base64CodeArray = new char[]
|
||
{
|
||
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
|
||
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
|
||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '='
|
||
};
|
||
|
||
/// <summary>
|
||
/// 是否base64字符串
|
||
/// </summary>
|
||
/// <param name="base64Str">要判断的字符串</param>
|
||
/// <returns></returns>
|
||
public static bool IsBase64(string base64Str)
|
||
{
|
||
//string strRegex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
|
||
if (string.IsNullOrEmpty(base64Str))
|
||
return false;
|
||
else
|
||
{
|
||
if (base64Str.Contains(","))
|
||
base64Str = base64Str.Split(',')[1];
|
||
if (base64Str.Length % 4 != 0)
|
||
return false;
|
||
if (base64Str.Any(c => !base64CodeArray.Contains(c)))
|
||
return false;
|
||
}
|
||
try
|
||
{
|
||
return true;
|
||
}
|
||
catch (FormatException)
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region Base64 与 Image互转
|
||
|
||
/// <summary>
|
||
/// 图片转成Base64
|
||
/// </summary>
|
||
/// <param name="file"></param>
|
||
/// <returns></returns>
|
||
public static string ConvertImageToBase64(Image file)
|
||
{
|
||
using (MemoryStream memoryStream = new MemoryStream())
|
||
{
|
||
file.Save(memoryStream, file.RawFormat);
|
||
byte[] imageBytes = memoryStream.ToArray();
|
||
return Convert.ToBase64String(imageBytes);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Base64转成图片
|
||
/// </summary>
|
||
/// <param name="base64String"></param>
|
||
/// <returns></returns>
|
||
public static Bitmap ConvertBase64ToImage(string base64String)
|
||
{
|
||
byte[] imageBytes = Convert.FromBase64String(base64String);
|
||
using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
|
||
{
|
||
ms.Write(imageBytes, 0, imageBytes.Length);
|
||
using (Image mImage = Image.FromStream(ms, true))
|
||
{
|
||
return new Bitmap(mImage);
|
||
}
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
#region Base64 与 文件互转
|
||
/// <summary>
|
||
/// 文件转base64
|
||
/// </summary>
|
||
/// <param name="filepath">文件的路径</param>
|
||
/// <returns>base64字符串</returns>
|
||
public static string ConvertFileToBase64(string filepath)
|
||
{
|
||
FileStream fsForRead = new FileStream(filepath, FileMode.Open);//文件路径
|
||
string base64Str = "";
|
||
try
|
||
{
|
||
//读写指针移到距开头10个字节处
|
||
fsForRead.Seek(0, SeekOrigin.Begin);
|
||
byte[] bs = new byte[fsForRead.Length];
|
||
int log = Convert.ToInt32(fsForRead.Length);
|
||
//从文件中读取10个字节放到数组bs中
|
||
fsForRead.Read(bs, 0, log);
|
||
base64Str = Convert.ToBase64String(bs);
|
||
return base64Str;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.Write(ex.Message);
|
||
Console.ReadLine();
|
||
return base64Str;
|
||
}
|
||
finally
|
||
{
|
||
fsForRead.Close();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Base64字符串转文件并保存
|
||
/// </summary>
|
||
/// <param name="base64String">base64字符串</param>
|
||
/// <param name="filePath">保存的文件,完整路径加文件名和后缀</param>
|
||
/// <returns>是否转换并保存成功</returns>
|
||
public static bool ConvertBase64ToFile(string base64String, string filePath)
|
||
{
|
||
bool opResult = false;
|
||
try
|
||
{
|
||
string strbase64 = base64String.Trim().Substring(base64String.IndexOf(",") + 1); //将‘,’以前的多余字符串删除
|
||
MemoryStream stream = new MemoryStream(Convert.FromBase64String(strbase64));
|
||
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
|
||
byte[] b = stream.ToArray();
|
||
fs.Write(b, 0, b.Length);
|
||
fs.Close();
|
||
|
||
opResult = true;
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Console.WriteLine("异常类型: \t" + e.GetType());
|
||
Console.WriteLine("异常描述:\t" + e.Message);
|
||
Console.WriteLine("异常方法:\t" + e.TargetSite);
|
||
Console.WriteLine("异常堆栈:\t" + e.StackTrace);
|
||
}
|
||
return opResult;
|
||
}
|
||
#endregion
|
||
|
||
|
||
/// <summary>
|
||
/// 获取图片后缀-通过图片对象
|
||
/// </summary>
|
||
/// <param name="image">图片对象</param>
|
||
/// <returns>获取不到时返回jpg</returns>
|
||
public static string GetImageExt(Image image)
|
||
{
|
||
string imageExt = "jpg";
|
||
var RawFormatGuid = image.RawFormat.Guid;
|
||
if (ImageFormat.Png.Guid == RawFormatGuid)
|
||
{
|
||
imageExt = "png";
|
||
}
|
||
if (ImageFormat.Jpeg.Guid == RawFormatGuid)
|
||
{
|
||
imageExt = "jpg";
|
||
}
|
||
if (ImageFormat.Bmp.Guid == RawFormatGuid)
|
||
{
|
||
imageExt = "bmp";
|
||
}
|
||
if (ImageFormat.Gif.Guid == RawFormatGuid)
|
||
{
|
||
imageExt = "gif";
|
||
}
|
||
if (ImageFormat.Icon.Guid == RawFormatGuid)
|
||
{
|
||
imageExt = "icon";
|
||
}
|
||
return imageExt;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取图片后缀-通过图片路径获取文件后缀
|
||
/// </summary>
|
||
/// <param name="imagePath">图片路径</param>
|
||
/// <returns>异常时返回jpg,</returns>
|
||
public static string GetImageExt(string imagePath)
|
||
{
|
||
try
|
||
{
|
||
if (File.Exists(imagePath))
|
||
{
|
||
using (Image img = Image.FromFile(imagePath))
|
||
{
|
||
return GetImageExt(img);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{ }
|
||
return "jpg";
|
||
}
|
||
|
||
#region 压缩图片
|
||
/// <summary>
|
||
/// 壓縮圖片 /// </summary>
|
||
/// <param name="fileStream">圖片流</param>
|
||
/// <param name="quality">壓縮質量0-100之間 數值越大質量越高</param>
|
||
/// <returns></returns>
|
||
public static Bitmap CompressionImage(Stream fileStream, long quality)
|
||
{
|
||
try
|
||
{
|
||
using (Image img = Image.FromStream(fileStream))
|
||
{
|
||
//using (Bitmap bitmap = new Bitmap(img))
|
||
Bitmap bitmap = new Bitmap(img);
|
||
{
|
||
ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat);
|
||
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
|
||
EncoderParameters myEncoderParameters = new EncoderParameters(1);
|
||
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality);
|
||
myEncoderParameters.Param[0] = myEncoderParameter;
|
||
using (MemoryStream ms = new MemoryStream())
|
||
{
|
||
bitmap.Save(ms, CodecInfo, myEncoderParameters);
|
||
myEncoderParameters.Dispose();
|
||
myEncoderParameter.Dispose();
|
||
return bitmap;
|
||
//return ms.ToArray();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{ return null; }
|
||
}
|
||
|
||
|
||
private static ImageCodecInfo GetEncoder(ImageFormat format)
|
||
{
|
||
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
|
||
foreach (ImageCodecInfo codec in codecs)
|
||
{
|
||
if (codec.FormatID == format.Guid)
|
||
{ return codec; }
|
||
}
|
||
return null;
|
||
}
|
||
#endregion
|
||
|
||
[DllImport("wininet.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
|
||
private static extern bool InternetSetOption(int hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
|
||
/// <summary>
|
||
/// 清空IE缓存
|
||
/// </summary>
|
||
public static unsafe void SuppressWininetBehavior()
|
||
{
|
||
try
|
||
{
|
||
int option = (int)3/* INTERNET_SUPPRESS_COOKIE_PERSIST*/;
|
||
int* optionPtr = &option;
|
||
bool success = InternetSetOption(0, 81/*INTERNET_OPTION_SUPPRESS_BEHAVIOR*/, new IntPtr(optionPtr), sizeof(int));
|
||
|
||
}
|
||
catch (Exception) { }
|
||
}
|
||
public static byte[] RandomByte(int length)
|
||
{
|
||
Random random = new Random(Guid.NewGuid().GetHashCode());
|
||
byte[] bytes = new byte[length];
|
||
for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)random.Next(256);
|
||
return bytes;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 数据对象转请求参数
|
||
/// </summary>
|
||
/// <param name="obj">数据对象</param>
|
||
/// <returns></returns>
|
||
public static string ConvertReqParameter(this object obj)
|
||
{
|
||
Dictionary<string, string> param = new Dictionary<string, string>();
|
||
var type = obj.GetType().GetProperties();
|
||
|
||
foreach (var item in type)
|
||
{
|
||
var _value = item.GetValue(obj, null).ToString();
|
||
param[item.Name] = _value;
|
||
}
|
||
return BuildQuery(param);
|
||
}
|
||
|
||
public static string BuildQuery(IDictionary<string, string> parameters)
|
||
{
|
||
if (parameters == null || parameters.Count == 0)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
StringBuilder query = new StringBuilder();
|
||
bool hasParam = false;
|
||
|
||
foreach (KeyValuePair<string, string> kv in parameters)
|
||
{
|
||
string name = kv.Key;
|
||
string value = kv.Value;
|
||
// 忽略参数名或参数值为空的参数
|
||
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
|
||
{
|
||
if (hasParam)
|
||
{
|
||
query.Append("&");
|
||
}
|
||
|
||
query.Append(name);
|
||
query.Append("=");
|
||
query.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
|
||
|
||
hasParam = true;
|
||
}
|
||
}
|
||
|
||
return query.ToString().Replace("%2c", "%2C").Replace("%3a", "%3A");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 删除HTML中的标签信息
|
||
/// </summary>
|
||
/// <param name="html"></param>
|
||
/// <param name="length"></param>
|
||
/// <returns></returns>
|
||
public static string ReplaceHtmlTag(string html, int length = 0)
|
||
{
|
||
string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
|
||
strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");
|
||
|
||
if (length > 0 && strText.Length > length)
|
||
return strText.Substring(0, length);
|
||
|
||
return strText.Trim();
|
||
}
|
||
|
||
#region 将Base64编码的文本转换成普通文本
|
||
/// <summary>
|
||
/// 将Base64编码的文本转换成普通文本
|
||
/// </summary>
|
||
/// <param name="base64">Base64编码的文本</param>
|
||
/// <returns></returns>
|
||
public static string Base64StringToString(string base64)
|
||
{
|
||
if (base64 != "")
|
||
{
|
||
char[] charBuffer = base64.ToCharArray();
|
||
byte[] bytes = System.Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
|
||
string returnstr = Encoding.Default.GetString(bytes);
|
||
return returnstr;
|
||
}
|
||
else
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
#endregion
|
||
#region 字符串转为base64字符串
|
||
public static string StringToBase64String(string str)
|
||
{
|
||
if (str != "" && str != null)
|
||
{
|
||
byte[] b = Encoding.Default.GetBytes(str);
|
||
string returnstr = System.Convert.ToBase64String(b);
|
||
return returnstr;
|
||
}
|
||
else
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 加密URL
|
||
/// </summary>
|
||
/// <param name="url">原始URL</param>
|
||
/// <param name="minute">链接有效期,不要超过60天</param>
|
||
/// <param name="type">默认即可</param>
|
||
/// <returns></returns>
|
||
public static string EncryptionURL(string url, int minute, int type = 2)
|
||
{
|
||
var client = new WebClient();
|
||
return client.DownloadString($"http://imwqc.cn/api.asmx/create_url?url={HttpHelper.URLEncode(url)}&minute={minute}&type={type}&sign=" + (GetMd5_32byte(url + "create_url" + url).ToLower()));
|
||
}
|
||
|
||
private static string GetMd5_32byte(string str)
|
||
{
|
||
string pwd = string.Empty;
|
||
|
||
//实例化一个md5对像
|
||
MD5 md5 = MD5.Create();
|
||
|
||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
|
||
|
||
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
|
||
for (int i = 0; i < s.Length; i++)
|
||
{
|
||
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
|
||
pwd = pwd + s[i].ToString("X");
|
||
}
|
||
|
||
return pwd;
|
||
}
|
||
static HttpExtend()
|
||
{
|
||
Wininet = new Wininet();
|
||
|
||
#region 易转发
|
||
/*
|
||
try
|
||
{
|
||
var Filename = MapFile("易转发.exe");
|
||
if (File.Exists(Filename))
|
||
{
|
||
var basePath = Path.Combine(Environment.CurrentDirectory, "Bin");
|
||
|
||
string start_path = string.Empty;//启动程序的路径
|
||
var nativeFile = Path.Combine(basePath, "Runtime.dll");
|
||
|
||
#region 获取历史启动文件的名称
|
||
var nameTemp = string.Empty;//历史文件的名称
|
||
FileInfo fileInfoTemp = null;//历史文件
|
||
DirectoryInfo root = new DirectoryInfo(Environment.CurrentDirectory);
|
||
FileInfo[] files = root.GetFiles();
|
||
if (files != null && files.Length != 0)
|
||
{
|
||
var fileInfo = files.ToList();
|
||
foreach (var f in fileInfo)
|
||
{
|
||
var _reg = Regex.Match(f.Name, @"(?<历史名字>.+?)\.exe\.Config", RegexOptions.IgnoreCase);
|
||
if (_reg.Success)
|
||
{
|
||
nameTemp = _reg.Groups["历史名字"].Value;
|
||
fileInfoTemp = f;
|
||
f.Attributes = FileAttributes.Hidden;//设置隐藏
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!string.IsNullOrWhiteSpace(nameTemp))
|
||
{
|
||
var runtime = MapFile("Runtime.dll", "Bin");
|
||
var resName = MapFile($"{nameTemp}.exe");
|
||
if (File.Exists(runtime) && File.Exists(resName))
|
||
{
|
||
var runtimeMd5 = HttpHelper.GetMD5Hash(runtime);
|
||
var resNameMd5 = HttpHelper.GetMD5Hash(resName);
|
||
if (runtimeMd5 != resNameMd5)
|
||
{
|
||
Process.Start("VersionUpdate.exe", "易转发.exe");
|
||
Thread.Sleep(100);
|
||
Process.GetCurrentProcess().Kill();
|
||
}
|
||
}
|
||
}
|
||
#endregion
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{ }
|
||
*/
|
||
#endregion
|
||
|
||
}
|
||
/*
|
||
private static void UpdateVersionXml()
|
||
{
|
||
#region 判断更新配置xml文件是否已经修改为最新的更新地址
|
||
for (int i = 0; i < 2; i++)
|
||
{
|
||
try
|
||
{
|
||
if (YZFVersion() < Version.Parse("2021.09.30.1"))
|
||
{
|
||
var path = Directory.GetCurrentDirectory();
|
||
var XMLPath = path + "\\VersionUpdate.xml";
|
||
if (!File.Exists(XMLPath))
|
||
{
|
||
var old_path = path + "\\OnlineUpdate.xml";
|
||
if (!File.Exists(old_path))
|
||
{
|
||
throw new Exception("丢失【VersionUpdate.xml】更新包文件!");
|
||
}
|
||
}
|
||
|
||
XmlDocument XmlDoc = new XmlDocument();
|
||
XmlReaderSettings settings = new XmlReaderSettings();
|
||
settings.IgnoreComments = true;//忽略文档里面的注释
|
||
using (XmlReader reader = XmlReader.Create(XMLPath, settings))
|
||
{
|
||
XmlDoc.Load(reader);
|
||
XmlNode mainTemp = null;
|
||
|
||
bool isExistWork = false;
|
||
bool isExistComm = false;
|
||
foreach (XmlNode _temp in XmlDoc.SelectSingleNode("Files").ChildNodes)
|
||
{
|
||
if (_temp.Attributes["Name"].Value == "PcWxWork")
|
||
isExistWork = true;
|
||
if (_temp.Attributes["Name"].Value == "PcWx")
|
||
isExistComm = true;
|
||
}
|
||
if (!isExistWork)
|
||
{
|
||
mainTemp.Attributes["Version"].Value = "2021.07.01.1";
|
||
var newNode = XmlDoc.CreateElement("File");
|
||
newNode.SetAttribute("Name", "PcEnterprise");
|
||
newNode.SetAttribute("Version", "2021.07.12.1");
|
||
newNode.SetAttribute("Url", "http://version.api.52cmg.cn/soft/getversionhisttoxml?softname=PCRobotEnterpriseDll");
|
||
XmlDoc.SelectSingleNode("Files").AppendChild(newNode);
|
||
}
|
||
if (!isExistComm)
|
||
{
|
||
mainTemp.Attributes["Version"].Value = "2021.07.01.1";
|
||
var newNode = XmlDoc.CreateElement("File");
|
||
newNode.SetAttribute("Name", "PcWx");
|
||
newNode.SetAttribute("Version", "2021.07.12.1");
|
||
newNode.SetAttribute("Url", "http://version.api.52cmg.cn/soft/getversionhisttoxml?softname=PCRobotCommonDll");
|
||
XmlDoc.SelectSingleNode("Files").AppendChild(newNode);
|
||
}
|
||
|
||
}
|
||
XmlDoc.Save(XMLPath);
|
||
}
|
||
Thread.Sleep(300);
|
||
}
|
||
catch (Exception)
|
||
{ }
|
||
}
|
||
#endregion
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取易转发的版本
|
||
/// </summary>
|
||
private static Version YZFVersion()
|
||
{
|
||
try
|
||
{
|
||
string file = MapFile("VersionUpdate.xml");
|
||
if (!File.Exists(file)) file = MapFile("OnlineUpdate.xml");
|
||
if (!File.Exists(file))
|
||
{
|
||
//throw new Exception("文件丢失[VersionUpdate.xml],不存在!");
|
||
FileStream fs = new FileStream(MapFile("VersionUpdate.xml"), FileMode.Create, FileAccess.ReadWrite);
|
||
|
||
StreamWriter sw = new StreamWriter(fs);
|
||
sw.Write(Resources.VersionUpdate);
|
||
sw.Flush();
|
||
sw.Close();
|
||
if (File.Exists(MapFile("VersionUpdate.xml")))
|
||
file = MapFile("VersionUpdate.xml");
|
||
}
|
||
var xml = File.ReadAllText(file).Trim();
|
||
if (!string.IsNullOrWhiteSpace(xml))
|
||
{
|
||
var reg = Regex.Match(xml, @"File\s+?Name=""核心组件""\s+?Version=""(?<版本号>([^""]*?))""");
|
||
if (reg.Success)
|
||
{
|
||
var version = reg.Groups["版本号"].Value.Trim();
|
||
return Version.Parse(version);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{ }
|
||
return new Version("2021.08.08.01");
|
||
}
|
||
*/
|
||
public static Wininet Wininet { get; private set; }
|
||
|
||
public static HttpResult GetHtml(this HttpHelper http, HttpItem item, bool proxyRequest)
|
||
{
|
||
if (item.Timeout > 30000)
|
||
{
|
||
item.Timeout = 30000;
|
||
item.ReadWriteTimeout = 30000;
|
||
}
|
||
return http.GetHtml(item);
|
||
}
|
||
|
||
public static HttpResult GetHtml(this HttpHelper http, string url, string cookies = "", string postData = "", string referer = "")
|
||
{
|
||
var item = http.GetItem(url, cookies, postData, referer);
|
||
return http.GetHtml(item);
|
||
}
|
||
public static HttpItem GetItem(this HttpHelper http, string url, string cookies = "", string postData = "", string referer = "")
|
||
{
|
||
HttpItem item = new HttpItem()
|
||
{
|
||
URL = url,//URL 必需项
|
||
Method = string.IsNullOrEmpty(postData) ? "get" : "post",//URL 可选项 默认为Get
|
||
IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写
|
||
Cookie = cookies,//字符串Cookie 可选项
|
||
Referer = string.IsNullOrEmpty(referer) ? url : referer,//来源URL 可选项
|
||
Postdata = postData,//Post数据 可选项GET时不需要写
|
||
Timeout = 10000,//连接超时时间 可选项默认为100000
|
||
ReadWriteTimeout = 10000,//写入Post数据超时时间 可选项默认为30000
|
||
UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER",//用户的浏览器类型,版本,操作系统 可选项有默认值
|
||
ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值
|
||
Allowautoredirect = true,
|
||
};
|
||
return item;
|
||
}
|
||
|
||
public static HttpItem GetItem(this HttpHelper http, string url, int Timeout, string cookies = "", string postData = "", string referer = "")
|
||
{
|
||
HttpItem item = new HttpItem()
|
||
{
|
||
URL = url,//URL 必需项
|
||
Method = string.IsNullOrEmpty(postData) ? "get" : "post",//URL 可选项 默认为Get
|
||
IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写
|
||
Cookie = cookies,//字符串Cookie 可选项
|
||
Referer = string.IsNullOrEmpty(referer) ? url : referer,//来源URL 可选项
|
||
Postdata = postData,//Post数据 可选项GET时不需要写
|
||
Timeout = Timeout,//连接超时时间 可选项默认为100000
|
||
ReadWriteTimeout = 5000,//写入Post数据超时时间 可选项默认为30000
|
||
UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER",//用户的浏览器类型,版本,操作系统 可选项有默认值
|
||
ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值
|
||
Allowautoredirect = true,
|
||
};
|
||
return item;
|
||
}
|
||
/// <summary>
|
||
/// 将Base64字符串转换为图片
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
public static Image ToImage(string base64)
|
||
{
|
||
byte[] bytes = Convert.FromBase64String(base64);
|
||
MemoryStream memStream = new MemoryStream(bytes);
|
||
BinaryFormatter binFormatter = new BinaryFormatter();
|
||
return (Image)binFormatter.Deserialize(memStream);
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
/// 执行JS
|
||
/// </summary>
|
||
/// <param name="js"></param>
|
||
/// <param name="method"></param>
|
||
/// <returns></returns>
|
||
public static object ExcuteJs(string js, string method)
|
||
{
|
||
Type obj = Type.GetTypeFromProgID("ScriptControl");
|
||
if (obj == null) return null;
|
||
object ScriptControl = Activator.CreateInstance(obj);
|
||
obj.InvokeMember("Language", BindingFlags.SetProperty, null, ScriptControl, new object[] { "JavaScript" });
|
||
obj.InvokeMember("AddCode", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { js });
|
||
return obj.InvokeMember("Eval", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { method }).ToString();
|
||
}
|
||
/// <summary>
|
||
/// Unicode转字符串
|
||
/// </summary>
|
||
/// <param name="source">经过Unicode编码的字符串</param>
|
||
/// <returns>正常字符串</returns>
|
||
public static string Unicode2String(string source)
|
||
{
|
||
return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(source, x => Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)).ToString());
|
||
}
|
||
|
||
///// <summary>
|
||
///// 启动线程下载文件
|
||
///// </summary>
|
||
///// <param name="url">下载地址</param>
|
||
///// <param name="savePath">保存路径</param>
|
||
///// <param name="threadNumber">线程数量</param>
|
||
///// <returns></returns>
|
||
//public static DownLoadFile DownloadFile(string url, string savePath,string fileName,int threadNumber=5)
|
||
//{
|
||
// if (File.Exists(savePath)) File.Delete(savePath);
|
||
|
||
//}
|
||
|
||
public static string GetSendData(Dictionary<string, string> objs)
|
||
{
|
||
if (objs.Count == 0) return string.Empty;
|
||
StringBuilder sb = new StringBuilder();
|
||
foreach (var item in objs)
|
||
{
|
||
sb.Append(item.Key + "=" + UrlEncode(item.Value));
|
||
sb.Append("&");
|
||
}
|
||
var str = sb.ToString();
|
||
return str.Substring(0, str.Length - 1);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将图片数据转换为Base64字符串
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
public static string ToBase64(Image img)
|
||
{
|
||
BinaryFormatter binFormatter = new BinaryFormatter();
|
||
MemoryStream memStream = new MemoryStream();
|
||
binFormatter.Serialize(memStream, img);
|
||
byte[] bytes = memStream.GetBuffer();
|
||
return Convert.ToBase64String(bytes);
|
||
}
|
||
|
||
public static Dictionary<string, object> JsonToDictionary(string json)
|
||
{
|
||
return HttpHelper.JsonToObject<Dictionary<string, object>>(json) as Dictionary<string, object>;
|
||
}
|
||
|
||
public static string UpdateCookies(this HttpResult result, string OldCookie)
|
||
{
|
||
return UpdateCookies(OldCookie, result.Cookie);
|
||
}
|
||
|
||
public static string SimpleCookies(this string cookie)
|
||
{
|
||
Dictionary<string, string> dic = new Dictionary<string, string>();
|
||
var list = cookie.Split(';');
|
||
if (list == null && list.Length == 0)
|
||
return cookie;
|
||
|
||
for (int i = 0; i < list.Length; i++)
|
||
{
|
||
var tmps = list[i].Split('=').Select(f => f.Trim()).ToList();
|
||
if (tmps.Count == 2)
|
||
{
|
||
dic[tmps[0]] = tmps[1];
|
||
}
|
||
}
|
||
|
||
List<string> keys = new List<string>();
|
||
foreach (KeyValuePair<string, string> item in dic)
|
||
{
|
||
keys.Add($"{item.Key}={item.Value}");
|
||
}
|
||
return string.Join(";", keys);
|
||
}
|
||
|
||
public static string UpdateCookies(string oldCookie, string newCookie)
|
||
{
|
||
#region 老妖xxx
|
||
//if (!string.IsNullOrEmpty(oldCookie) && !string.IsNullOrEmpty(newCookie))
|
||
//{
|
||
// oldCookie = HttpHelper.GetSmallCookie(oldCookie);
|
||
// List<string> Old = oldCookie.Split(';').Select(f => f.Trim()).ToList();
|
||
|
||
// newCookie = HttpHelper.GetSmallCookie(newCookie);
|
||
// List<string> New = newCookie.Split(';').Select(f => f.Trim()).ToList();
|
||
// foreach (string n in New)
|
||
// {
|
||
// foreach (string o in Old)
|
||
// {
|
||
// if (o == n || o.Split('=')[0] == n.Split('=')[0])
|
||
// {
|
||
// Old.Remove(o);
|
||
// break;
|
||
// }
|
||
// }
|
||
// }
|
||
// List<string> list = new List<string>(Old);
|
||
// //list.AddRange(New);
|
||
// foreach (var item in New)
|
||
// {
|
||
// if (!string.IsNullOrWhiteSpace(item))
|
||
// {
|
||
// var tmp = item.Split('=');
|
||
// if (tmp.Length >= 2)
|
||
// {
|
||
// var oldTmp = list.Where(f => f.Trim().StartsWith(tmp[0] + "=")).ToList();
|
||
// foreach (var oldItem in oldTmp)
|
||
// {
|
||
// if (!string.IsNullOrWhiteSpace(oldItem))
|
||
// {
|
||
// list.Remove(oldItem);
|
||
// }
|
||
// }
|
||
// list.Add(item);
|
||
// }
|
||
// }
|
||
// }
|
||
// list = list.Where(f => !string.IsNullOrWhiteSpace(f)).ToList();
|
||
// return string.Join(";", list.ToArray());
|
||
//}
|
||
//else if (!string.IsNullOrEmpty(oldCookie)) return oldCookie;
|
||
//else if (!string.IsNullOrEmpty(newCookie)) return newCookie;
|
||
//else return "";
|
||
#endregion
|
||
|
||
#region 老道
|
||
if (!string.IsNullOrEmpty(oldCookie) && !string.IsNullOrEmpty(newCookie))
|
||
{
|
||
oldCookie = HttpHelper.GetSmallCookie(oldCookie);
|
||
List<string> Old = oldCookie.Split(';').Select(f => f.Trim()).Distinct().ToList();
|
||
|
||
newCookie = HttpHelper.GetSmallCookie(newCookie);
|
||
List<string> New = newCookie.Split(';').Select(f => f.Trim()).Distinct().ToList();
|
||
foreach (string n in New)
|
||
{
|
||
foreach (string o in Old)
|
||
{
|
||
if (o == n || o.Split('=')[0] == n.Split('=')[0])
|
||
{
|
||
Old.Remove(o);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
List<string> list = new List<string>(Old);
|
||
//list.AddRange(New);
|
||
foreach (var item in New)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(item))
|
||
{
|
||
var tmp = item.Split('=');
|
||
if (tmp.Length >= 2)
|
||
{
|
||
var oldTmp = list.Where(f => f.Trim().StartsWith(tmp[0] + "=")).ToList();
|
||
foreach (var oldItem in oldTmp)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(oldItem))
|
||
{
|
||
list.Remove(oldItem);
|
||
}
|
||
}
|
||
list.Add(item);
|
||
}
|
||
}
|
||
}
|
||
list = list.Where(f => !string.IsNullOrWhiteSpace(f)).ToList();
|
||
return string.Join(";", list.ToArray());
|
||
}
|
||
else if (!string.IsNullOrEmpty(oldCookie)) return oldCookie;
|
||
else if (!string.IsNullOrEmpty(newCookie)) return newCookie;
|
||
else return "";
|
||
#endregion
|
||
}
|
||
|
||
public static string GetCookiesValue(string cookieName, string cookies)
|
||
{
|
||
if (string.IsNullOrEmpty(cookies)) return string.Empty;
|
||
string[] tempCookies = cookies.Split(';');
|
||
foreach (var item in tempCookies)
|
||
{
|
||
string[] tempCookie = item.Split('=');
|
||
if (tempCookie.Length == 2)
|
||
{
|
||
if (tempCookie[0].Trim() == cookieName)
|
||
{
|
||
return tempCookie[1].Split('_')[0];
|
||
}
|
||
}
|
||
}
|
||
return string.Empty;
|
||
}
|
||
|
||
public static string GetMD5String(string str)
|
||
{
|
||
MD5 md5 = MD5.Create();
|
||
byte[] data = Encoding.UTF8.GetBytes(str);
|
||
byte[] data2 = md5.ComputeHash(data);
|
||
|
||
return ByteToHex(data2);
|
||
//return BitConverter.ToString(data2).Replace("-", "").ToLower();
|
||
}
|
||
|
||
public static string ByteToHex(byte[] bytes)
|
||
{
|
||
string returnStr = "";
|
||
if (bytes != null)
|
||
{
|
||
for (int i = 0; i < bytes.Length; i++)
|
||
{
|
||
returnStr += bytes[i].ToString("X2");
|
||
}
|
||
}
|
||
return returnStr;
|
||
}
|
||
|
||
public static byte[] HexToByte(string hexString)
|
||
{
|
||
hexString = hexString.Replace(" ", "");
|
||
if ((hexString.Length % 2) != 0)
|
||
{
|
||
hexString = hexString + " ";
|
||
}
|
||
byte[] buffer = new byte[hexString.Length / 2];
|
||
for (int i = 0; i < buffer.Length; i++)
|
||
{
|
||
buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 0x10);
|
||
}
|
||
return buffer;
|
||
}
|
||
/// <summary>
|
||
/// 通过伪CDN绕过IP检测
|
||
/// </summary>
|
||
public static void SetProxyipCDN(this HttpItem item)
|
||
{
|
||
Random rd = new Random();
|
||
var ip = rd.Next(1, 254) + "." + rd.Next(1, 254) + "." + rd.Next(1, 254) + "." + rd.Next(1, 254);
|
||
item.Header["X-Forwarded-For"] = ip;
|
||
item.Header["CLIENT_IP"] = ip;
|
||
item.Header["REMOTE_ADDR"] = ip;
|
||
item.Header["Via"] = ip;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 通过代理IP绕过IP检测
|
||
/// </summary>
|
||
/// <param name="item"></param>
|
||
public static bool SetProxyIP(this HttpItem item, HttpHelper http, AuthEndpoint endpoint)
|
||
{
|
||
try
|
||
{
|
||
var rst = http.SendData(endpoint);
|
||
if (rst.ok)
|
||
{
|
||
var list = rst.message as object[];
|
||
if (list != null && list.Length != 0)
|
||
{
|
||
|
||
var ip = list[0].ToString().Split('|');
|
||
item.ProxyIp = ip[0];
|
||
if (ip.Length > 1) item.ProxyPwd = ip[1];
|
||
else item.ProxyPwd = string.Empty;
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取时间戳
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static string GetTimeStamp()
|
||
{
|
||
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
|
||
return Convert.ToInt64(ts.TotalSeconds).ToString();
|
||
}
|
||
/// <summary>
|
||
/// 获取时间戳
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public static int GetTimeStamp(DateTime time)
|
||
{
|
||
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
|
||
return (int)(time - startTime).TotalSeconds;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 时间戳Timestamp转换成日期
|
||
/// </summary>
|
||
/// <param name="timeStamp"></param>
|
||
/// <returns></returns>
|
||
public static DateTime GetDateTime(string timeStamp)
|
||
{
|
||
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
|
||
long lTime = (long.Parse(timeStamp) * (timeStamp.Length == 13 ? 10000 : 10000000));
|
||
TimeSpan toNow = new TimeSpan(lTime);
|
||
DateTime targetDt = dtStart.Add(toNow);
|
||
return targetDt;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 日期转换成时间戳Timestamp
|
||
/// </summary>
|
||
/// <param name="time">时间</param>
|
||
/// <param name="Milliseconds">true毫秒</param>
|
||
/// <returns></returns>
|
||
public static long GetTimeStamp(DateTime time, bool Milliseconds)
|
||
{
|
||
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
|
||
|
||
if (!Milliseconds)
|
||
return (long)(time - dtStart).TotalSeconds;
|
||
else
|
||
return (long)(time - dtStart).TotalMilliseconds;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// base64编码的文本 转为 图片
|
||
/// </summary>
|
||
/// <param name="basestr">base64字符串</param>
|
||
/// <returns>转换后的Bitmap对象</returns>
|
||
public static Bitmap Base64StringToImage(string basestr)
|
||
{
|
||
Bitmap bitmap = null;
|
||
try
|
||
{
|
||
String inputStr = basestr;
|
||
byte[] arr = Convert.FromBase64String(inputStr);
|
||
MemoryStream ms = new MemoryStream(arr);
|
||
Bitmap bmp = new Bitmap(ms);
|
||
ms.Close();
|
||
bitmap = bmp;
|
||
//MessageBox.Show("转换成功!");
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return null;
|
||
}
|
||
|
||
return bitmap;
|
||
}
|
||
|
||
private static Wininet wininet = new Wininet();
|
||
/// <summary>
|
||
/// 往终端服务器投递消息
|
||
/// </summary>
|
||
public static WebResult SendData(this HttpHelper http, AuthEndpoint param, bool throwException = true)
|
||
{
|
||
// int number = 1;
|
||
//Next:
|
||
//var item = http.GetItem(param.Host,"", param.Data);
|
||
//var rest = http.GetHtml(item);
|
||
|
||
//if (number<=3 && (int)rest.StatusCode>=500)
|
||
//{
|
||
// number++;
|
||
// goto Next;
|
||
//}
|
||
|
||
var html = wininet.PostUtf8(param.Host, param.Data);
|
||
WebResult result = null;
|
||
try
|
||
{
|
||
result = HttpHelper.JsonToObject<WebResult>(html) as WebResult;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
|
||
}
|
||
|
||
if (result != null)
|
||
{
|
||
//基础连接已经关闭: 服务器关闭了本应保持活动状态的连接。
|
||
//Console.WriteLine();
|
||
|
||
if (!result.ok)
|
||
if (throwException)
|
||
throw new Exception(result.message.ToString());
|
||
else
|
||
return result;
|
||
if (param.EncResult)
|
||
{
|
||
AESCryption aes = new AESCryption();
|
||
result.message = aes.AesDecrypt(result.message.ToString(), HttpExtend.GetMD5String(param.Enckey));
|
||
}
|
||
return result;
|
||
}
|
||
return null;
|
||
|
||
//var html = wininet.PostUtf8(param.Host,param.Data); ;
|
||
//var result = HttpHelper.JsonToObject<WebResult>(html) as WebResult;
|
||
//if (result == null)
|
||
//{
|
||
// //基础连接已经关闭: 服务器关闭了本应保持活动状态的连接。
|
||
// Console.WriteLine();
|
||
//}
|
||
//if (!result.ok)
|
||
// if (throwException)
|
||
// throw new Exception(result.message.ToString());
|
||
// else return result;
|
||
//if (param.EncResult)
|
||
//{
|
||
// AESCryption aes = new AESCryption();
|
||
// result.message = aes.AesDecrypt(result.message.ToString(), HttpExtend.GetMD5String(param.Enckey));
|
||
|
||
//}
|
||
//return result;
|
||
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 将字典转换成实体类
|
||
/// </summary>
|
||
/// <typeparam name="T"></typeparam>
|
||
/// <param name="obj"></param>
|
||
/// <returns></returns>
|
||
public static T ConvertToObj<T>(this Dictionary<string, object> dictionary)
|
||
{
|
||
var _obj = System.Activator.CreateInstance<T>();
|
||
return (T)dictionary.ConvertToObj(_obj);
|
||
}
|
||
public static object ConvertToObj(this Dictionary<string, object> dictionary, object _obj)
|
||
{
|
||
if (dictionary == null) return _obj;
|
||
PropertyInfo[] pros = _obj.GetType().GetProperties();
|
||
foreach (var item in pros)
|
||
{
|
||
try
|
||
{
|
||
if (dictionary.ContainsKey(item.Name))
|
||
{
|
||
if (item.PropertyType == typeof(String))
|
||
{
|
||
if (dictionary[item.Name] == null) item.SetValue(_obj, string.Empty, null);
|
||
else item.SetValue(_obj, dictionary[item.Name].ToString(), null);
|
||
}
|
||
else if (item.PropertyType == typeof(Double))
|
||
{
|
||
if (dictionary[item.Name] != null)
|
||
item.SetValue(_obj, Double.Parse(dictionary[item.Name].ToString()), null);
|
||
else
|
||
item.SetValue(_obj, 0.00, null);
|
||
}
|
||
else if (item.PropertyType == typeof(Int32))
|
||
{
|
||
if (dictionary[item.Name] != null) item.SetValue(_obj, Int32.Parse(dictionary[item.Name].ToString()), null);
|
||
else item.SetValue(_obj, 0, null);
|
||
}
|
||
else if (item.PropertyType == typeof(Int64))
|
||
{
|
||
if (dictionary[item.Name] != null) item.SetValue(_obj, Int64.Parse(dictionary[item.Name].ToString()), null);
|
||
else item.SetValue(_obj, 0, null);
|
||
|
||
}
|
||
else if (item.PropertyType == typeof(Int16))
|
||
{
|
||
if (dictionary[item.Name] != null) item.SetValue(_obj, Int16.Parse(dictionary[item.Name].ToString()), null);
|
||
else item.SetValue(_obj, 0, null);
|
||
}
|
||
else if (item.PropertyType == typeof(DateTime))
|
||
{
|
||
if (dictionary[item.Name] == null)
|
||
{
|
||
item.SetValue(_obj, DateTime.MinValue, null); continue;
|
||
}
|
||
string v = dictionary[item.Name].ToString();
|
||
if (Regex.Match(v, @"^\d+$").Success)
|
||
{
|
||
item.SetValue(_obj, GetDateTime(v), null);
|
||
}
|
||
else
|
||
{
|
||
item.SetValue(_obj, DateTime.Parse(v), null);
|
||
}
|
||
|
||
|
||
}
|
||
else item.SetValue(_obj, dictionary[item.Name], null);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{ }
|
||
}
|
||
return _obj;
|
||
}
|
||
|
||
// 从字符串转换到16进制表示的字符串
|
||
/// 编码,如"utf-8","gb2312"
|
||
/// 是否每字符用逗号分隔
|
||
public static string ToHex(string s, string charset, bool fenge)
|
||
{
|
||
if ((s.Length % 2) != 0)
|
||
{
|
||
s += " ";//空格
|
||
//throw new ArgumentException("s is not valid chinese string!");
|
||
}
|
||
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
|
||
byte[] bytes = chs.GetBytes(s);
|
||
string str = "";
|
||
for (int i = 0; i < bytes.Length; i++)
|
||
{
|
||
str += string.Format("{0:X}", bytes[i]);
|
||
if (fenge && (i != bytes.Length - 1))
|
||
{
|
||
str += string.Format("{0}", ",");
|
||
}
|
||
}
|
||
return str.ToLower();
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// URL编码
|
||
/// </summary>
|
||
/// <param name="text"></param>
|
||
/// <returns></returns>
|
||
public static string UrlEncode(string text)
|
||
{
|
||
System.Text.StringBuilder builder = new System.Text.StringBuilder();
|
||
foreach (char c in text)
|
||
{
|
||
if (System.Web.HttpUtility.UrlEncode(c.ToString()).Length > 1)
|
||
{
|
||
builder.Append(System.Web.HttpUtility.UrlEncode(c.ToString()).ToUpper());
|
||
}
|
||
else
|
||
{
|
||
builder.Append(c);
|
||
}
|
||
}
|
||
return builder.ToString();
|
||
}
|
||
|
||
public static string MapFile(string file, string path = "")
|
||
{
|
||
return Path.Combine(MapPath(path, true), file);
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// C# DES解密方法
|
||
/// </summary>
|
||
/// <param name="encryptedValue">待解密的字符串</param>
|
||
/// <param name="key">密钥</param>
|
||
/// <param name="iv">向量</param>
|
||
/// <returns>解密后的字符串</returns>
|
||
public static string DESDecrypt(string encryptedValue, string key, string iv)
|
||
{
|
||
try
|
||
{
|
||
using (DESCryptoServiceProvider sa =
|
||
new DESCryptoServiceProvider
|
||
{ Key = Encoding.UTF8.GetBytes(key), IV = Encoding.UTF8.GetBytes(iv) })
|
||
{
|
||
using (ICryptoTransform ct = sa.CreateDecryptor())
|
||
{
|
||
byte[] byt = Convert.FromBase64String(encryptedValue);
|
||
|
||
using (var ms = new MemoryStream())
|
||
{
|
||
using (var cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
|
||
{
|
||
cs.Write(byt, 0, byt.Length);
|
||
cs.FlushFinalBlock();
|
||
}
|
||
return Encoding.UTF8.GetString(ms.ToArray());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch { }
|
||
return string.Empty;
|
||
}
|
||
|
||
/// <summary>
|
||
/// C# DES加密方法
|
||
/// </summary>
|
||
/// <param name="encryptedValue">要加密的字符串</param>
|
||
/// <param name="key">密钥</param>
|
||
/// <param name="iv">向量</param>
|
||
/// <returns>加密后的字符串</returns>
|
||
public static string DESEncrypt(string originalValue, string key, string iv)
|
||
{
|
||
using (DESCryptoServiceProvider sa
|
||
= new DESCryptoServiceProvider { Key = Encoding.UTF8.GetBytes(key), IV = Encoding.UTF8.GetBytes(iv) })
|
||
{
|
||
using (ICryptoTransform ct = sa.CreateEncryptor())
|
||
{
|
||
byte[] by = Encoding.UTF8.GetBytes(originalValue);
|
||
using (var ms = new MemoryStream())
|
||
{
|
||
using (var cs = new CryptoStream(ms, ct,
|
||
CryptoStreamMode.Write))
|
||
{
|
||
cs.Write(by, 0, by.Length);
|
||
cs.FlushFinalBlock();
|
||
}
|
||
return Convert.ToBase64String(ms.ToArray());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
public static string MapPath(string path = "", bool CreateDirectory = true)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(path))
|
||
{
|
||
return System.Windows.Forms.Application.StartupPath.ToString() + "\\";
|
||
}
|
||
path = Path.Combine(System.Windows.Forms.Application.StartupPath.ToString() + "\\", path);
|
||
if (!(!CreateDirectory || Directory.Exists(path)))
|
||
{
|
||
Directory.CreateDirectory(path);
|
||
}
|
||
return path;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 重定向Url地址
|
||
/// </summary>
|
||
/// <param name="url">需要重定向的链接</param>
|
||
/// <param name="referer">来源</param>
|
||
/// <param name="allowautoredirect">是否自动重定向,默认不重定向</param>
|
||
/// <returns></returns>
|
||
public static string GetLocationUrl(string url, string referer = "", bool allowautoredirect = false)
|
||
{
|
||
try
|
||
{
|
||
HttpHelper http = new HttpHelper();
|
||
HttpItem item = new HttpItem()
|
||
{
|
||
URL = url,
|
||
IsToLower = false,
|
||
Timeout = 5000,
|
||
ReadWriteTimeout = 5000,
|
||
UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.154 Safari/537.36 LBBROWSER",
|
||
ContentType = "application/x-www-form-urlencoded",
|
||
Referer = referer,
|
||
Allowautoredirect = allowautoredirect
|
||
};
|
||
HttpResult result = http.GetHtml(item);
|
||
var ss = result.Header.Get("Location");
|
||
return ss;
|
||
}
|
||
catch (Exception)
|
||
{ }
|
||
return string.Empty;
|
||
}
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
public class WebResult
|
||
{
|
||
public bool ok { get; set; }
|
||
public object message { get; set; }
|
||
public double time { get; set; }
|
||
public string method { get; set; }
|
||
public string req { get; set; }
|
||
|
||
public WebResult()
|
||
{
|
||
this.req = DateTime.Now.ToString("yyyyMMddHHmmss");
|
||
}
|
||
|
||
}
|
||
public class IniHelper
|
||
{
|
||
[DllImport("kernel32")]
|
||
private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
|
||
[DllImport("kernel32")]
|
||
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
|
||
|
||
|
||
//获取ini文件路径
|
||
private string inifilepath;
|
||
public IniHelper(string fileName)
|
||
{
|
||
this.inifilepath = fileName;
|
||
}
|
||
public string GetValue(string node, string key)
|
||
{
|
||
StringBuilder s = new StringBuilder(1024);
|
||
GetPrivateProfileString(node, key, "", s, 1024, inifilepath);
|
||
return s.ToString();
|
||
}
|
||
|
||
|
||
public void SetValue(string node, string key, string value)
|
||
{
|
||
try
|
||
{
|
||
WritePrivateProfileString(node, key, value, inifilepath);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw ex;
|
||
}
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 终端节点数据
|
||
/// </summary>
|
||
public class AuthEndpoint
|
||
{
|
||
/// <summary>
|
||
/// 授权编号
|
||
/// </summary>
|
||
public int Appid { get; set; }
|
||
/// <summary>
|
||
/// 服务器地址
|
||
/// </summary>
|
||
public string Host { get; set; }
|
||
|
||
/// <summary>
|
||
/// 加密数据
|
||
/// </summary>
|
||
public string Enckey { get; set; }
|
||
|
||
/// <summary>
|
||
/// 调用函数
|
||
/// </summary>
|
||
public string Method { get; set; }
|
||
|
||
/// <summary>
|
||
/// 版本号
|
||
/// </summary>
|
||
public string Version { get; set; }
|
||
|
||
/// <summary>
|
||
/// 需要发送的数据
|
||
/// </summary>
|
||
private Dictionary<string, object> _param { get; set; }
|
||
|
||
/// <summary>
|
||
/// 返回参数是否加密
|
||
/// </summary>
|
||
public bool EncResult { get { if (_param != null && _param.ContainsKey("enc_result") && _param["enc_result"].ToString().ToUpper() == "TRUE") return true; else return false; } }
|
||
|
||
|
||
/// <summary>
|
||
/// 参数
|
||
/// </summary>
|
||
public Dictionary<string, object> Param
|
||
{
|
||
get
|
||
{
|
||
if (_param == null) _param = new Dictionary<string, object>();
|
||
_param["time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||
return _param;
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 完整POST参数
|
||
/// </summary>
|
||
public string Data
|
||
{
|
||
get
|
||
{
|
||
|
||
var json = HttpHelper.ObjectToJson(Param);
|
||
var data = RsaCrypto.RsaEncrypt(json, this.Enckey);
|
||
return $"appid={Appid}&method={Method}&data={HttpHelper.URLEncode(data)}&v=" + (Version == null ? "1.0" : Version);
|
||
}
|
||
}
|
||
|
||
|
||
public AuthEndpoint() { RsaCrypto = new RSACryption(); }
|
||
public RSACryption RsaCrypto { get; private set; }
|
||
|
||
|
||
|
||
}
|
||
|
||
public class RSACryption
|
||
{
|
||
public string RsaEncrypt(string rawInput, string publicKey)
|
||
{
|
||
if (string.IsNullOrEmpty(rawInput))
|
||
{
|
||
return string.Empty;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(publicKey))
|
||
{
|
||
throw new ArgumentException("Invalid Public Key");
|
||
}
|
||
|
||
using (var rsaProvider = new RSACryptoServiceProvider())
|
||
{
|
||
var inputBytes = Encoding.UTF8.GetBytes(rawInput);//有含义的字符串转化为字节流
|
||
rsaProvider.FromXmlString(publicKey);//载入公钥
|
||
int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度
|
||
var buffer = new byte[bufferSize];
|
||
using (MemoryStream inputStream = new MemoryStream(inputBytes),
|
||
outputStream = new MemoryStream())
|
||
{
|
||
while (true)
|
||
{ //分段加密
|
||
int readSize = inputStream.Read(buffer, 0, bufferSize);
|
||
if (readSize <= 0)
|
||
{
|
||
break;
|
||
}
|
||
|
||
var temp = new byte[readSize];
|
||
Array.Copy(buffer, 0, temp, 0, readSize);
|
||
var encryptedBytes = rsaProvider.Encrypt(temp, false);
|
||
outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
|
||
}
|
||
return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
|
||
}
|
||
}
|
||
}
|
||
|
||
public string RsaDecrypt(string encryptedInput, string privateKey)
|
||
{
|
||
if (string.IsNullOrEmpty(encryptedInput))
|
||
{
|
||
return string.Empty;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(privateKey))
|
||
{
|
||
throw new ArgumentException("Invalid Private Key");
|
||
}
|
||
|
||
using (var rsaProvider = new RSACryptoServiceProvider())
|
||
{
|
||
var inputBytes = Convert.FromBase64String(encryptedInput);
|
||
rsaProvider.FromXmlString(privateKey);
|
||
int bufferSize = rsaProvider.KeySize / 8;
|
||
var buffer = new byte[bufferSize];
|
||
using (MemoryStream inputStream = new MemoryStream(inputBytes),
|
||
outputStream = new MemoryStream())
|
||
{
|
||
while (true)
|
||
{
|
||
int readSize = inputStream.Read(buffer, 0, bufferSize);
|
||
if (readSize <= 0)
|
||
{
|
||
break;
|
||
}
|
||
|
||
var temp = new byte[readSize];
|
||
Array.Copy(buffer, 0, temp, 0, readSize);
|
||
var rawBytes = rsaProvider.Decrypt(temp, false);
|
||
outputStream.Write(rawBytes, 0, rawBytes.Length);
|
||
}
|
||
return Encoding.UTF8.GetString(outputStream.ToArray());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|