From 0a401cbc33dd175f6aeb12869ef60d4e4fb09bf9 Mon Sep 17 00:00:00 2001
From: qiyun996 <237024888@qq.com>
Date: Tue, 25 Apr 2023 11:13:33 +0800
Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=9F=BA=E7=A1=80=E7=B1=BB?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
EC.Util/Common/DateUnit.cs | 439 +++++++++++++++++++++++++
EC.Util/Common/FileUnit.cs | 367 +++++++++++++++++++++
EC.Util/Common/LogUnit.cs | 67 ++++
EC.Util/EC.Util.csproj | 1 +
EC.Util/Net/APICallBack.cs | 39 +++
EC.Util/Net/HttpServer.cs | 362 ++++++++++++++++++++
EC.Util/Net/NetUnit.cs | 657 +++++++++++++++++++++++++++++++++++++
JiLinApp/JiLinApp.csproj | 3 +
8 files changed, 1935 insertions(+)
create mode 100644 EC.Util/Common/DateUnit.cs
create mode 100644 EC.Util/Common/FileUnit.cs
create mode 100644 EC.Util/Common/LogUnit.cs
create mode 100644 EC.Util/Net/APICallBack.cs
create mode 100644 EC.Util/Net/HttpServer.cs
create mode 100644 EC.Util/Net/NetUnit.cs
diff --git a/EC.Util/Common/DateUnit.cs b/EC.Util/Common/DateUnit.cs
new file mode 100644
index 0000000..f2e6ac8
--- /dev/null
+++ b/EC.Util/Common/DateUnit.cs
@@ -0,0 +1,439 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+/*******************************************************/
+/*Project:基础类库
+Module :时间函数库
+Description :
+Date : 2008-6-3 15:09:12
+Create : Lxc
+Update : 2015-12-31
+TODO : */
+/*******************************************************/
+
+
+namespace System
+{
+ ///
+ /// 日期时间操作单元
+ ///
+ public partial class DateUnit
+ {
+
+ ///
+ /// 1970-1-1
+ ///
+ public static DateTime InitDate()
+ {
+ return new DateTime(1970, 1, 1);
+ }
+
+ ///
+ /// 默认当前日期
+ ///
+ public static DateTime DefDate()
+ {
+ return DateTime.Now;
+ }
+ ///
+ /// 格式化后的当前日期
+ ///
+ public static string DefFormatDate()
+ {
+ return FormatDate(DefDate());
+ }
+ ///
+ ///格式化当前时间
+ ///
+ public static string DefFormatDateTime()
+ {
+ return FormatDateTime(DefDate());
+ }
+
+ ///
+ /// 格式化后的 当前月1号 日期格式yyyy-MM-01
+ ///
+ public static string DefMonthBegFormat()
+ {
+ return DefDate().ToString("yyyy-MM-01");
+ }
+ ///
+ /// 字符串格式->格式化为当前日期
+ ///
+ ///
+ ///
+ public static string FormatDate(string Indate)
+ {
+ DateTime nowDate = DefDate();
+
+ if (Indate != null && Indate != "")
+ {
+ nowDate = ToDate(Indate);
+ }
+
+ return FormatDate(nowDate);
+
+
+ }
+ ///
+ /// 格式化为 日期格式yyyy-MM-dd
+ ///
+ ///
+ ///
+ public static string FormatDate(DateTime Indate)
+ {
+
+ if (!Indate.Equals(null))
+ {
+ return Indate.ToString("yyyy-MM-dd");
+ }
+ else
+ {
+ return DefFormatDate();
+ }
+
+ }
+ ///
+ /// 格式化为 日期时间格式yyyy-MM-dd HH:mm:ss
+ ///
+ ///
+ ///
+ public static string FormatDateTime(DateTime Indate)
+ {
+
+ if (!Indate.Equals(null))
+ {
+ return Indate.ToString("yyyy-MM-dd HH:mm:ss");
+ }
+ else
+ {
+ return DefFormatDate();
+ }
+
+ }
+ ///
+ /// 格式化时间 毫秒
+ ///
+ ///
+ ///
+ public static string FormatDateTimefff(DateTime Indate)
+ {
+
+ if (!Indate.Equals(null))
+ {
+ return Indate.ToString("yyyy-MM-dd HH:mm:ss fff");
+ }
+ else
+ {
+ return DefFormatDate();
+ }
+
+ }
+
+
+ #region 时间函数
+
+ ///
+ /// 是不是时间格式
+ ///
+ ///
+ ///
+ public static bool IsDate(string datetm)
+ {
+ bool result = false;
+ try
+ {
+ DateTime dateTime = Convert.ToDateTime(datetm);
+ result = true;
+ }
+ catch
+ {
+ result = false;
+
+ }
+ return result;
+ }
+
+
+ ///
+ /// 将字符串转化成日期,如果输入的字符串不是日期时,则返回1970-1-1
+ ///
+ ///
+ ///
+ public static DateTime ToDate(string str)
+ {
+ if (str == null || str == "")
+ return DefDate();
+ else
+ {
+ DateTime dt = DefDate();
+ if (DateTime.TryParse(str, out dt) == false)
+ return DefDate();
+ else
+ return dt;
+ }
+ }
+
+ ///
+ /// 将对象转化成日期,如果输入的对象不是日期时,则返回1970-1-1
+ ///
+ ///
+ ///
+ public static DateTime ToDate(object obj)
+ {
+ DateTime Result = DefDate();
+ if (!obj.Equals(null))
+ {
+ try
+ {
+ Result = (DateTime)obj;
+ }
+ catch (Exception ex)
+ {
+ return DefDate();
+ }
+ //if (DateTime.TryParse(obj.ToString(), out Result) == false)
+ // return DefDate;
+ }
+ return Result;
+ }
+
+ ///
+ /// 将对象转化成日期,如果输入的对象不是日期时,则返回1900-1-1
+ ///
+ ///
+ ///
+ public static DateTime ToDate(System.Nullable obj)
+ {
+ if (!obj.Equals(null))
+ {
+
+ return (DateTime)obj;
+ }
+ else
+ {
+ return DefDate();
+ }
+
+ }
+
+
+ ///
+ /// 20070101-->2007-01-01
+ ///
+ ///
+ ///
+ public static string StrTodate(string Str)
+ {
+ string stryear, strmon, strday;
+ try
+ {
+ stryear = Str.Remove(4, 4);
+ Str = Str.Remove(0, 4);
+ strmon = Str.Remove(2, 2);
+ strday = Str.Remove(0, 2);
+ stryear = stryear + "-" + strmon + "-" + strday;
+ return stryear;
+ }
+ catch
+ {
+ return DefFormatDate();
+ }
+
+ }
+
+
+
+ #endregion
+
+ #region 周计算
+
+ ///
+ /// 周几
+ ///
+ ///
+ ///
+ public static string DayOfWeek(DateTime curDay)
+ {
+
+
+ string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
+ string week = weekdays[Convert.ToInt32(curDay.DayOfWeek)];
+
+ return week;
+
+ }
+
+ ///
+ /// 第几周
+ ///
+ ///
+ ///
+ public static int WeekOfYear(DateTime curDay)
+ {
+
+ int firstdayofweek = Convert.ToInt32(Convert.ToDateTime(curDay.Year.ToString() + "-" + "1-1").DayOfWeek);
+
+ int days = curDay.DayOfYear;
+ int daysOutOneWeek = days - (7 - firstdayofweek);
+
+ if (daysOutOneWeek <= 0)
+ {
+ return 1;
+ }
+ else
+ {
+ int weeks = daysOutOneWeek / 7;
+ if (daysOutOneWeek % 7 != 0)
+ weeks++;
+
+ return weeks + 1;
+ }
+ }
+
+ #region 返回某年某月最后一天
+ ///
+ /// 返回某年某月最后一天
+ ///
+ /// 年份
+ /// 月份
+ /// 日
+ public static int GetMonthLastDate(int year, int month)
+ {
+ DateTime lastDay = new DateTime(year, month, new System.Globalization.GregorianCalendar().GetDaysInMonth(year, month));
+ int Day = lastDay.Day;
+ return Day;
+ }
+ #endregion
+
+
+ #endregion
+
+
+ #region 返回时间差
+ ///
+ /// 返回时间差 秒
+ ///
+ ///
+ ///
+ ///
+ public static double DateDiffSeconds(DateTime begDateTime, DateTime endDateTime)
+ {
+
+ try
+ {
+ TimeSpan ts = endDateTime - begDateTime;
+ return ts.TotalSeconds;
+ }
+ catch (Exception)
+ {
+ return 0;
+ }
+ }
+ ///
+ /// 返回时间差 分钟
+ ///
+ ///
+ ///
+ ///
+ public static double DateDiffMinutes(DateTime begDateTime, DateTime endDateTime)
+ {
+
+ try
+ {
+ TimeSpan ts = endDateTime - begDateTime;
+ return ts.TotalMinutes;
+ }
+ catch (Exception)
+ {
+ return 0;
+ }
+ }
+ public static double DateDiffHours(DateTime begDateTime, DateTime endDateTime)
+ {
+
+ try
+ {
+ TimeSpan ts = endDateTime - begDateTime;
+ return ts.TotalHours;
+ }
+ catch (Exception)
+ {
+ return 0;
+ }
+ }
+ public static double DateDifDays(DateTime begDateTime, DateTime endDateTime)
+ {
+
+ try
+ {
+ TimeSpan ts = endDateTime - begDateTime;
+ return ts.TotalDays;
+ }
+ catch (Exception)
+ {
+ return 0;
+ }
+ }
+ #endregion
+
+ ///
+ /// Unix时间戳
+ ///
+ /// 毫秒
+ public static long UnixTime()
+ {
+ System.DateTime time = DateTime.Now;
+ System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
+ long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
+ return t;
+ }
+ ///
+ /// 将c# DateTime时间格式转换为Unix时间戳格式
+ ///
+ /// 时间
+ /// 毫秒
+ public static long DateTimeToUnixTime(System.DateTime time)
+ {
+ System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
+ long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
+ return t;
+ }
+ ///
+ /// 时间戳转为C#格式时间
+ ///
+ ///
+ ///
+ public static DateTime UnixTimeToDateTime(long timeStamp)
+ {
+ DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
+ long lTime = timeStamp * 10000;
+ TimeSpan toNow = new TimeSpan(lTime);
+ return dtStart.Add(toNow);
+ }
+
+ ///
+ /// Unix时间戳 时间格式化 为日期
+ ///
+ ///
+ ///
+ public static string FormatDateUnixTime(long timeStamp)
+ {
+ DateTime dtStart = UnixTimeToDateTime(timeStamp);
+ return FormatDate(dtStart);
+ }
+ ///
+ /// Unix时间戳 时间格式化 为时间
+ ///
+ ///
+ ///
+ public static string FormatDateTimeUnixTime(long timeStamp)
+ {
+ DateTime dtStart = UnixTimeToDateTime(timeStamp);
+ return FormatDateTime(dtStart);
+ }
+
+ }
+}
diff --git a/EC.Util/Common/FileUnit.cs b/EC.Util/Common/FileUnit.cs
new file mode 100644
index 0000000..c32b9d9
--- /dev/null
+++ b/EC.Util/Common/FileUnit.cs
@@ -0,0 +1,367 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.IO;
+using System.Web;
+/*******************************************************/
+/*Project:基础类库
+Module :文件操作库
+Description : 文本读写,日志
+Date : 2008-6-3 15:09:12
+Create : Lxc
+Update : 2014-12-31
+TODO : */
+/*******************************************************/
+namespace System
+{
+ ///
+ /// 文件操作单元
+ ///
+ public partial class FileUnit
+ {
+ static readonly string AppFilepatch = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
+ ///
+ /// 创建目录
+ ///
+ ///
+ ///
+ public static bool CreateDir(string fullPath)
+ {
+ if (!Directory.Exists(fullPath))
+ {
+ try
+ {
+ Directory.CreateDirectory(fullPath);
+ return true;
+ }
+ catch (Exception ex)
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+ //删除文件名 获取路径
+ public static string GetDirectory(string fullPath)
+ {
+ return Path.GetDirectoryName(fullPath);
+ //return allFileName.Substring(0, allFileName.LastIndexOf('\\'));
+ }
+ ///
+ /// 得到文件名称
+ ///
+ ///
+ ///
+ public static string GetFileName(string fullPath)
+ {
+ return Path.GetFileName(fullPath);
+ }
+ ///
+ /// 得到扩展名
+ ///
+ ///
+ ///
+ public static string GetFileExt(string fullPath)
+ {
+ return Path.GetExtension(fullPath);
+ }
+ ///
+ /// 得到名称没有扩展名
+ ///
+ ///
+ ///
+ public static string GetFileNameNoExt(string fullPath)
+ {
+ return Path.GetFileNameWithoutExtension(fullPath);
+ }
+ ///
+ /// 复制文件
+ ///
+ ///
+ ///
+ ///
+ public static string CopyFile(string sourceFileName, string destFileName)
+ {
+ try
+ {
+ if (File.Exists(sourceFileName))
+ {
+ string destDirectory = GetDirectory(destFileName);// destFileName.Substring(0, destFileName.LastIndexOf('\\'));//删除文件名 获取路径
+ bool createDir = CreateDir(destDirectory);
+ if (createDir)
+ {
+ File.Copy(sourceFileName, destFileName);
+ }
+ else
+ {
+ return "文件路径" + destFileName + "不正确!";
+ }
+ }
+ else
+ {
+ return "文件路径" + sourceFileName + "不存在!";
+ }
+ return "";
+ }
+ catch (Exception ex)
+ {
+ return ex.Message;
+ }
+
+
+ }
+ ///
+ /// 得到路径 没有扩展名
+ ///
+ ///
+ ///
+ public static string GetPathNoExt(string rptPath)
+ {
+ string rtpDir = GetDirectory(rptPath);
+ string disFileName = GetFileNameNoExt(rptPath);
+ string disPatch = rtpDir + "\\" + disFileName;// +".docx";
+ return disPatch;
+ }
+ ///
+ /// 读取文本
+ ///
+ ///
+ ///
+ public static string ReadtxtFile(string filename)
+ {
+
+ try
+ {
+ if (File.Exists(filename))
+ {
+ // Create an instance of StreamReader to read from a file.
+ // The using statement also closes the StreamReader.
+ using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
+ {
+ return sr.ReadToEnd();
+ }
+ }
+ else LogUnit.Error(typeof(FileUnit),"no exists " + filename);
+
+ }
+ catch (Exception e)
+ {
+ LogUnit.Error(typeof(FileUnit), e.ToString());
+ }
+ return "";
+
+ }
+
+ ///
+ /// 读取多行文本
+ ///
+ ///
+ ///
+ public static List ReadtxtLinesFile(string filename)
+ {
+ List filtxtLines = new List();
+ try
+ {
+ if (File.Exists(filename))
+ {
+ // Create an instance of StreamReader to read from a file.
+ // The using statement also closes the StreamReader.
+ using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
+ {
+ String line;
+ // Read and display lines from the file until the end of
+ // the file is reached.
+ while ((line = sr.ReadLine()) != null)
+ {
+ filtxtLines.Add(line);
+ }
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ LogUnit.Error(typeof(FileUnit), e.ToString());
+ }
+ return filtxtLines;
+ }
+
+ ///
+ /// 读取多行文本
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static bool WritetxtFileLine(string filepatch,string filename, List txtLines)
+ {
+
+ List filtxtLines = new List();
+ try
+ {
+
+
+ if (!Directory.Exists(filepatch))
+ {
+ Directory.CreateDirectory(filepatch);
+ }
+ using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8))
+ {
+ foreach (string str in txtLines)
+ {
+ sw.WriteLine(str);
+ }
+ sw.Close();
+ }
+
+ }
+ catch (Exception e)
+ {
+ LogUnit.Error(typeof(FileUnit), e.ToString());
+ return false;
+ }
+ return true;
+ }
+ ///
+ /// 写入文本
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static bool WritetxtFile(string filepatch, string filename, string text)
+ {
+
+ List filtxtLines = new List();
+ try
+ {
+
+ if (!Directory.Exists(filepatch))
+ {
+ Directory.CreateDirectory(filepatch);
+ }
+
+ using (StreamWriter sw = new StreamWriter(filepatch + filename, false, System.Text.Encoding.UTF8))
+ {
+
+ sw.Write(text);
+
+ sw.Close();
+ }
+
+ }
+ catch (Exception e)
+ {
+ LogUnit.Error(typeof(FileUnit), e.ToString());
+ return false;
+ }
+ return true;
+ }
+
+ private static bool Log(string subfilepatch,string logmessage)
+ {
+
+ try
+ {
+ string logfilePath = AppFilepatch + "Log\\" + subfilepatch ;
+ if (!Directory.Exists(logfilePath))
+ {
+ Directory.CreateDirectory(logfilePath);
+ }
+ using (StreamWriter sw = new StreamWriter(logfilePath + DateTime.Now.ToString("yyyyMMdd") + ".txt", true, System.Text.Encoding.UTF8))
+ {
+ sw.WriteLine(DateTime.Now.ToString() + " : " + logmessage);
+ sw.Close();
+ }
+ }
+ catch (Exception e)
+ {
+ return false;
+ }
+ return true;
+ }
+
+ //支付日志
+ public static void PayLog(string log)
+ {
+ string path = "PayLog\\";
+ Log(path, log);
+ }
+
+ //订单日志
+ public static void OrderLog(string log)
+ {
+ string path = "OrderLog\\";
+ Log(path, log);
+ }
+
+ //写入日志
+ public static void Log(string log)
+ {
+ string path = "";
+ Log(path, log);
+ }
+ public static void WebLog(string log)
+ {
+ Log(log);
+ }
+
+ //public static void WebLog(string log)
+ //{
+ // string path = HttpContext.Current.Server.MapPath(".")+"Web\\";
+ // Log(path, log);
+ //}
+
+ public static void ErrLog(string log)
+ {
+ string subpath = "ErrLog\\";
+ Log(subpath, log);
+ }
+ public static void HisLog(string log)
+ {
+ string subpath = "HisLog\\";
+ Log(subpath, log);
+ }
+
+
+ public static void Package(string log)
+ {
+ string path = "Package\\";
+ Log(path, log);
+ }
+
+
+ public static void EPS(string log)
+ {
+ string path = "EPS\\";
+ Log(path, log);
+ }
+ public static void AllLog(string log)
+ {
+ string path = "AllLog\\";
+ Log(path, log);
+ }
+ public static bool Exists(string path)
+ {
+ return File.Exists(path);
+ }
+ public static void DeleteFile(string path)
+ {
+ try
+ {
+ if (File.Exists(path))
+ {
+ File.Delete(path);
+ }
+ else
+ {
+ LogUnit.Error(typeof(FileUnit), "路径不存在" + path);
+ }
+ }
+ catch (Exception ex)
+ {
+ LogUnit.Error(typeof(FileUnit), ex.ToString());
+ }
+ }
+ }
+}
diff --git a/EC.Util/Common/LogUnit.cs b/EC.Util/Common/LogUnit.cs
new file mode 100644
index 0000000..5995fd7
--- /dev/null
+++ b/EC.Util/Common/LogUnit.cs
@@ -0,0 +1,67 @@
+using log4net;
+using log4net.Config;
+using System;
+using System.IO;
+
+namespace System;
+
+public static class LogUnit
+{
+ private static readonly ILog logger;
+
+ static LogUnit()
+ {
+ string fileName = Path.Combine("config", "log4net.Config");
+ XmlConfigurator.Configure(new FileInfo(fileName));
+ logger = LogManager.GetLogger(typeof(LogUnit));
+ }
+
+ public static void Init()
+ {
+ }
+
+ public static void Debug(string msg)
+ {
+ logger.Debug(msg);
+ }
+
+ public static void Info(string msg)
+ {
+ logger.Info(msg);
+ }
+
+ public static void Warn(string msg)
+ {
+ logger.Warn(msg);
+ }
+
+ public static void Error(string msg)
+ {
+ logger.Error(msg);
+ }
+
+ public static void Fatal(string msg)
+ {
+ logger.Fatal(msg);
+ }
+
+ public static void Error(Exception e)
+ {
+ logger.Error(e);
+ }
+ ///
+ /// 输出日志到Log4Net
+ ///
+ ///
+ ///
+ public static void Error(Type t, Exception ex)
+ {
+
+ logger.Error("Error", ex);
+ }
+ public static void Error(Type t, string logMessage)
+ {
+
+ logger.Error(logMessage);
+ }
+}
\ No newline at end of file
diff --git a/EC.Util/EC.Util.csproj b/EC.Util/EC.Util.csproj
index b14e9c0..ccbf668 100644
--- a/EC.Util/EC.Util.csproj
+++ b/EC.Util/EC.Util.csproj
@@ -68,6 +68,7 @@
+
diff --git a/EC.Util/Net/APICallBack.cs b/EC.Util/Net/APICallBack.cs
new file mode 100644
index 0000000..ea48d39
--- /dev/null
+++ b/EC.Util/Net/APICallBack.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EC.Util.Net
+{
+ public class APICallBack
+ {
+ public string reqCode { get; set; }
+ ///
+ /// 任务单号
+ ///
+ public string taskCode { get; set; }
+ ///
+ /// AGV状态指令
+ ///
+ public string method { get; set; }
+ public string reqTime { get; set; }
+ public string wbCode { get; set; }
+ ///
+ /// AGV编号
+ ///
+ public string robotCode { get; set; }
+ ///
+ /// 请求AGV接口后返回的成功失败或其他消息
+ ///
+ public string message { get; set; }
+ ///
+ /// 请求AGV接口后返回的任务单号
+ ///
+ public string data { get; set; }
+ ///
+ /// 请求AGV接口后返回的任务状态
+ ///
+ public string code { get; set; }
+ }
+}
diff --git a/EC.Util/Net/HttpServer.cs b/EC.Util/Net/HttpServer.cs
new file mode 100644
index 0000000..8cc5a28
--- /dev/null
+++ b/EC.Util/Net/HttpServer.cs
@@ -0,0 +1,362 @@
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace EC.Util.Net
+{
+ public class HttpServer
+ {
+
+ public event EventHandler OnRecData; //定义一个委托类型的事件
+ #region
+
+ public string Host { get; set; }
+ public string port { get; set; }
+ private string _webHomeDir = "";
+ private HttpListener listener;
+ private Thread listenThread;
+ private string directorySeparatorChar = Path.DirectorySeparatorChar.ToString();
+ public string ImageUploadPath { get; set; }
+
+
+ ///
+ /// 设置监听端口,重启服务生效
+ ///
+ //public string Port
+ //{
+ // get { return this.port; }
+ // set
+ // {
+ // int p;
+ // if (string.IsNullOrEmpty(value) || !int.TryParse(value, out p))
+ // {
+ // throw new Exception("给http监听器赋值的端口号无效!");
+ // }
+ // this.port = value;
+ // }
+ //}
+ ///
+ /// http服务根目录
+ ///
+ public string WebHomeDir
+ {
+ get { return this._webHomeDir; }
+ set
+ {
+ if (!Directory.Exists(value))
+ throw new Exception("http服务器设置的根目录不存在!");
+ this._webHomeDir = value;
+ }
+ }
+ ///
+ /// 服务器是否在运行
+ ///
+ public bool IsRunning
+ {
+ get { return (listener == null) ? false : listener.IsListening; }
+ }
+ #endregion
+
+ #region
+ public HttpServer( string host, string port, string webHomeDir, string imageUploadPath)
+ {
+
+ this.Host = host;
+ this.port = port;
+ this._webHomeDir = webHomeDir;
+ ImageUploadPath = imageUploadPath;
+ listener = new HttpListener();
+ }
+
+ public bool AddPrefixes(string uriPrefix)
+ {
+ string uri = "http://" + uriPrefix + ":" + this.port + "/";
+ if (listener.Prefixes.Contains(uri)) return false;
+ listener.Prefixes.Add(uri);
+ return true;
+ }
+
+ ///
+ /// 启动服务
+ ///
+ public void Start()
+ {
+ try
+ {
+ if (listener.IsListening)
+ return;
+ if (!string.IsNullOrEmpty(Host) && Host.Length > 0)
+ listener.Prefixes.Add("http://" + Host + ":" + this.port + "/"); //AGV/AGVAPI/agvCallback/
+ else if (listener.Prefixes == null || listener.Prefixes.Count == 0)
+ listener.Prefixes.Add("http://localhost:" + this.port + "/");
+ listener.Start();
+
+ listenThread = new Thread(AcceptClient);
+ listenThread.Name = "signserver";
+ listenThread.Start();
+ Log("开启接口监听服务:"+ this.port);
+
+ }
+ catch (Exception ex)
+ {
+ LogUnit.Error(ex.Message);
+ }
+
+
+ }
+ ///
+ /// 停止服务
+ ///
+ public void Stop()
+ {
+ try
+ {
+ if (listener != null)
+ {
+ //listener.Close();
+ //listener.Abort();
+ listener.Stop();
+
+ }
+ }
+ catch (Exception ex)
+ {
+ LogUnit.Error(ex.Message);
+ }
+ }
+
+ ///
+ /// /接受客户端请求
+ ///
+ void AcceptClient()
+ {
+ //int maxThreadNum, portThreadNum;
+ ////线程池
+ //int minThreadNum;
+ //ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
+ //ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
+ //Console.WriteLine("最大线程数:{0}", maxThreadNum);
+ //Console.WriteLine("最小空闲线程数:{0}", minThreadNum);
+
+ while (listener.IsListening)
+ {
+ try
+ {
+ HttpListenerContext context = listener.GetContext();
+ //new Thread(HandleRequest).Start(context);
+ ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context);
+ }
+ catch
+ {
+
+ }
+ }
+
+ }
+ #endregion
+
+ #region HandleRequest
+ //处理客户端请求
+ private void HandleRequest(object ctx)
+ {
+ HttpListenerContext context = ctx as HttpListenerContext;
+ HttpListenerResponse response = context.Response;
+ HttpListenerRequest request = context.Request;
+ try
+ {
+ context.Request.Headers.Add("Access-Control-Allow-Origin", "*");
+ context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
+ string rawUrl = System.Web.HttpUtility.UrlDecode(request.RawUrl);
+ int paramStartIndex = rawUrl.IndexOf('?');
+ if (paramStartIndex > 0)
+ rawUrl = rawUrl.Substring(0, paramStartIndex);
+ else if (paramStartIndex == 0)
+ rawUrl = "";
+ if ( rawUrl.EndsWith("agvCallback") ) {
+
+ APICallBack apiCallBack = new APICallBack();
+
+ apiCallBack.reqCode = context.Request.QueryString["reqCode"];
+ apiCallBack.taskCode = context.Request.QueryString["taskCode"];
+ apiCallBack.method = context.Request.QueryString["method"];
+ apiCallBack.wbCode = context.Request.QueryString["wbCode"];
+ apiCallBack.robotCode = context.Request.QueryString["robotCode"];
+
+ //接收POST参数 2020-5-30
+ Stream stream = context.Request.InputStream;
+ System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
+ //整理应该是接收到的值
+ string body = reader.ReadToEnd();
+ //FileUnit.Log(body);
+ //if (JsonUtil.JSONToObject(body)!=null)
+ //{
+ // apiCallBack = JsonUnit.JSONToObject(body);
+ //}
+
+ response.ContentType = "text/html;charset=utf-8";
+ using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
+ {
+ OnRecData?.Invoke(this, apiCallBack);
+
+ string str = Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data = "调用成功", Message = "成功", ReqCode = apiCallBack.reqCode });
+ writer.Write(str);
+ }
+
+ ////Response
+ //context.Response.StatusCode = 200;
+ //context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
+ //context.Response.ContentType = "application/json";
+ //context.Response.ContentEncoding = Encoding.UTF8;
+ //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new { Code = "0", Data= "调用成功", Message = "成功" , ReqCode ="",}));
+ //context.Response.ContentLength64 = buffer.Length;
+ //var output = context.Response.OutputStream;
+ //output.Write(buffer, 0, buffer.Length);
+ //output.Close();
+
+ }
+ else if (string.Compare(rawUrl, "/ImageUpload", true) == 0)
+ {
+ #region 上传图片
+ string fileName = context.Request.QueryString["name"];
+ string filePath = ImageUploadPath + "\\" + DateTime.Now.ToString("yyMMdd_HHmmss_ffff")
+ + Path.GetExtension(fileName).ToLower();
+ using (var stream = request.InputStream)
+ {
+ using (var br = new BinaryReader(stream))
+ {
+ WriteStreamToFile(br, filePath, request.ContentLength64);
+ }
+ }
+ response.ContentType = "text/html;charset=utf-8";
+
+ using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
+ {
+ writer.WriteLine("接收完成!");
+ }
+
+ #endregion
+ }
+ else
+ {
+ #region 网页请求
+ string InputStream = "";
+ using (var streamReader = new StreamReader(request.InputStream))
+ {
+ InputStream = streamReader.ReadToEnd();
+ }
+ string filePath = "";
+ if (string.IsNullOrEmpty(rawUrl) || rawUrl.Length == 0 || rawUrl == "/")
+ filePath = WebHomeDir + directorySeparatorChar + "Index.html";
+ else
+ filePath = WebHomeDir + rawUrl.Replace("/", directorySeparatorChar);
+ if (!File.Exists(filePath))
+ {
+ response.ContentLength64 = 0;
+ response.StatusCode = 404;
+ response.Abort();
+ }
+ else
+ {
+ response.StatusCode = 200;
+ string exeName = Path.GetExtension(filePath);
+ response.ContentType = GetContentType(exeName);
+ FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
+ int byteLength = (int)fileStream.Length;
+ byte[] fileBytes = new byte[byteLength];
+ fileStream.Read(fileBytes, 0, byteLength);
+ fileStream.Close();
+ fileStream.Dispose();
+ response.ContentLength64 = byteLength;
+ response.OutputStream.Write(fileBytes, 0, byteLength);
+ response.OutputStream.Close();
+ }
+ #endregion
+ }
+ }
+ catch (Exception ex)
+ {
+ LogUnit.Error(ex.Message);
+ response.StatusCode = 200;
+ response.ContentType = "text/plain";
+ using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
+ {
+ writer.WriteLine("接收完成!");
+ }
+ }
+ try
+ {
+ response.Close();
+ }
+ catch (Exception ex)
+ {
+ LogUnit.Error(ex.Message);
+ }
+ }
+ #endregion
+
+ #region GetContentType
+ ///
+ /// 获取文件对应MIME类型
+ ///
+ /// 文件扩展名,如.jpg
+ ///
+ protected string GetContentType(string fileExtention)
+ {
+ if (string.Compare(fileExtention, ".html", true) == 0
+ || string.Compare(fileExtention, ".htm", true) == 0)
+ return "text/html;charset=utf-8";
+ else if (string.Compare(fileExtention, ".js", true) == 0)
+ return "application/javascript";
+ else if (string.Compare(fileExtention, ".css", true) == 0)
+ return "text/css";
+ else if (string.Compare(fileExtention, ".png", true) == 0)
+ return "image/png";
+ else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0)
+ return "image/jpeg";
+ else if (string.Compare(fileExtention, ".gif", true) == 0)
+ return "image/gif";
+ else if (string.Compare(fileExtention, ".swf", true) == 0)
+ return "application/x-shockwave-flash";
+ else if (string.Compare(fileExtention, ".pdf", true) == 0)
+ return "application/pdf";
+ else
+ return "";//application/octet-stream
+ }
+ #endregion
+
+ #region WriteStreamToFile
+ //const int ChunkSize = 1024 * 1024;
+ private void WriteStreamToFile(BinaryReader br, string fileName, long length)
+ {
+ byte[] fileContents = new byte[] { };
+ var bytes = new byte[length];
+ int i = 0;
+ while ((i = br.Read(bytes, 0, (int)length)) != 0)
+ {
+ byte[] arr = new byte[fileContents.LongLength + i];
+ fileContents.CopyTo(arr, 0);
+ Array.Copy(bytes, 0, arr, fileContents.Length, i);
+ fileContents = arr;
+ }
+
+ using (var fs = new FileStream(fileName, FileMode.Create))
+ {
+ using (var bw = new BinaryWriter(fs))
+ {
+ bw.Write(fileContents);
+ }
+ }
+ }
+ #endregion
+ public void Log(string msg, bool isErr = false)
+ {
+ //(msg, isErr);
+ }
+ }
+}
diff --git a/EC.Util/Net/NetUnit.cs b/EC.Util/Net/NetUnit.cs
new file mode 100644
index 0000000..0efb98b
--- /dev/null
+++ b/EC.Util/Net/NetUnit.cs
@@ -0,0 +1,657 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Net;
+using System.IO;
+
+namespace System
+{
+ ///
+ /// 网络操作单元
+ ///
+ public partial class NetUnit
+ {
+
+ #region 获取主机名称
+ ///
+ /// 获取本地机器名称
+ ///
+ /// 机器名称
+ public static string GetHostName()
+ {
+ string hostName = "";
+ try
+ {
+ hostName = Dns.GetHostName();
+ return hostName;
+ }
+ catch
+ {
+ return null;
+ }
+ }
+ #endregion
+
+ #region 获取本地主机IP
+ ///
+ /// 获取本地机器IP
+ ///
+ /// IP地址
+ public static string GetHostIp()
+ {
+ string localIp = "";
+ try
+ {
+ System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
+ for (int i = 0; i < addressList.Length; i++)
+ {
+ localIp += addressList[i].ToString();
+ }
+ return localIp;
+ }
+ catch
+ {
+ return null;
+ }
+
+ }
+ #endregion
+
+ #region 穿过代理服务器获得Ip地址,如果有多个IP,则第一个是用户的真实IP,其余全是代理的IP,用逗号隔开
+ //public static string getRealIp()
+ //{
+ // string UserIP;
+ // if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"]!=null) //得到穿过代理服务器的ip地址
+ // {
+
+ // UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
+ // }
+ // else
+ // {
+ // UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
+ // }
+ // return UserIP;
+ //}
+ #endregion
+
+
+ #region 获取主机MAC地址
+ ///
+ /// 获取本机MAC地址
+ ///
+ /// string null
+ public static string GetHostMac()
+ {
+ //string mac = "";
+ //try
+ //{
+ // ManagementClass mc;
+ // mc=new ManagementClass("Win32_NetworkAdapterConfiguration");
+ // ManagementObjectCollection moc=mc.GetInstances();
+ // foreach(ManagementObject mo in moc)
+ // {
+ // if(mo["IPEnabled"].ToString()=="True")
+ // mac=mo["MacAddress"].ToString();
+ // }
+ // return mac;
+ //}
+ //catch
+ //{
+ // return null;
+ //}
+ return null;
+
+ }
+ #endregion
+
+ #region 获取本机IP
+ public static string GetLocalIp()
+ {
+ //Page.Request.UserHostName
+ return null;
+ }
+ #endregion
+
+
+ ///
+ /// C# 验证IP
+ ///
+ ///
+ ///
+ public static bool IsIP(string ip)
+ {
+ string pattern = @"(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))";
+ Regex objRe = new Regex(pattern);
+ Match objMa = objRe.Match(ip);
+ if(!objMa.Success)
+ {
+ return false;
+ }
+ else return true;
+ }
+ public static string PingResult(string ip)
+ {
+ System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
+ System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
+ options.DontFragment = true;
+ string data = "Lxc";
+ byte[] buffer = Encoding.ASCII.GetBytes(data);
+ //Wait seconds for a reply.
+ int timeout = 100;
+
+ System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
+ return reply.Status.ToString();
+
+
+ }
+
+ #region 获取指定WEB页面
+ /// GET方法获取页面
+ /// 函数名:GetWebUrl
+ /// 功能描述:WebClient 获取页面
+ /// 处理流程:
+ /// 算法描述:
+ /// 作 者: lxc
+ /// 日 期: 2012-10-09
+ /// 修 改:
+ /// 日 期:
+ /// 版 本:
+ public static string GetWebUrl(string strurl)
+ {
+ WebClient webClient = new WebClient();
+ try
+ {
+ webClient.Credentials = CredentialCache.DefaultCredentials;
+ Byte[] pageData = webClient.DownloadData(strurl);
+ //string pageHtml = Encoding.UTF8.GetString(pageData);
+ string pageHtml = Encoding.Default.GetString(pageData);
+ return pageHtml;
+
+ }
+ catch (WebException webEx)
+ {
+ return "error_GetWebUrl:" + webEx.ToString();
+ }
+ finally
+ {
+ webClient = null;
+ }
+
+
+ }
+ #endregion
+
+ #region PostUrl(String url, String paramList)
+ ///
+ /// POST方法获取页面
+ ///
+ ///
+ /// 格式: a=xxx&b=xxx&c=xxx
+ ///
+ public static string PostUrl(String url, String paramList)
+ {
+ HttpWebResponse res = null;
+ string strResult = "";
+ try
+ {
+
+ HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
+ req.Method = "POST";
+ req.KeepAlive = true;
+ req.ContentType = "application/x-www-form-urlencoded";
+ //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)";
+ CookieContainer cookieCon = new CookieContainer();
+ req.CookieContainer = cookieCon;
+ StringBuilder UrlEncoded = new StringBuilder();
+ Char[] reserved = { '?', '=', '&' };
+ byte[] SomeBytes = null;
+ if (paramList != null)
+ {
+ int i = 0, j;
+ while (i < paramList.Length)
+ {
+ j = paramList.IndexOfAny(reserved, i);
+ if (j == -1)
+ {
+ // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length-i)));
+ UrlEncoded.Append((paramList.Substring(i, paramList.Length - i)));
+ break;
+ }
+ // UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j-i)));
+ UrlEncoded.Append((paramList.Substring(i, j - i)));
+ UrlEncoded.Append(paramList.Substring(j, 1));
+ i = j + 1;
+ }
+ SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString());
+ req.ContentLength = SomeBytes.Length;
+ Stream newStream = req.GetRequestStream();
+ newStream.Write(SomeBytes, 0, SomeBytes.Length);
+ newStream.Close();
+ }
+ else
+ {
+ req.ContentLength = 0;
+ }
+ res = (HttpWebResponse)req.GetResponse();
+ Stream ReceiveStream = res.GetResponseStream();
+ // Encoding encode = System.Text.Encoding.Default;//GetEncoding("utf-8");
+ string encodeheader = res.ContentType;
+ string encodestr = System.Text.Encoding.Default.HeaderName;
+ if ((encodeheader.IndexOf("charset=") >= 0) && (encodeheader.IndexOf("charset=GBK") == -1) && (encodeheader.IndexOf("charset=gbk") == -1))
+ {
+ int i = encodeheader.IndexOf("charset=");
+ encodestr = encodeheader.Substring(i + 8);
+ }
+ Encoding encode = System.Text.Encoding.GetEncoding(encodestr);//GetEncoding("utf-8");
+
+ StreamReader sr = new StreamReader(ReceiveStream, encode);
+ Char[] read = new Char[256];
+ int count = sr.Read(read, 0, 256);
+ while (count > 0)
+ {
+ String str = new String(read, 0, count);
+ strResult += str;
+ count = sr.Read(read, 0, 256);
+ }
+ }
+ catch (Exception e)
+ {
+ strResult = e.ToString();
+ }
+ finally
+ {
+ if (res != null)
+ {
+ res.Close();
+ }
+ }
+ return strResult;
+ }
+
+ #endregion
+
+
+
+
+ #region 下载指定WEB页面
+ /// GET方法获取页面
+ /// 函数名:GetFileUrl
+ /// 功能描述:WebClient 下载文件
+ /// 处理流程:
+ /// 算法描述:
+ /// 作 者: lxc
+ /// 日 期: 2012-10-09
+ /// 修 改:
+ /// 日 期:
+ /// 版 本:
+ public static Boolean GetFileUrl(string strurl, string filename)
+ {
+ try
+ {
+
+ WebClient webClient = new WebClient();
+ // webClient.Credentials = CredentialCache.DefaultCredentials;
+ webClient.DownloadFile(strurl, filename);
+ return true;
+
+ }
+ catch (WebException webex)
+ {
+ return false;// "error_GetWebUrl:" + webEx.ToString();
+ }
+
+ }
+ #endregion
+
+
+ #region 获取图片
+
+
+ public static Stream GetImage(String url)
+ {
+
+ HttpWebResponse res = null;
+
+
+ try
+ {
+ HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
+
+
+
+ res = (HttpWebResponse)req.GetResponse();
+ Stream ReceiveStream = res.GetResponseStream();
+ return ReceiveStream;
+
+ }
+ catch
+ {
+ return null;
+ }
+ finally
+ {
+ }
+ }
+
+ /// GET方法获取页面
+ /// 函数名:GetImage
+ /// 功能描述:GET方法获取页面
+ /// 处理流程:
+ /// 算法描述:
+ /// 作 者: 杨栋
+ /// 日 期: 2006-11-21 09:00
+ /// 修 改: 2007-01-29 17:00 2006-12-05 17:00
+ /// 日 期:
+ /// 版 本:
+ ///
+ #region GetImage(String url,string cookieheader)
+ ///
+ ///
+ ///
+ /// 目标url
+ /// 输入Cookie
+ ///
+ public static byte[] GetImage(String url, string cookieheader)
+ {
+ // outcookieheader="";
+
+ HttpWebResponse res = null;
+
+
+ try
+ {
+ HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
+ // req.Method = "GET";
+ // req.ContentType = "application/x-www-form-urlencoded";
+ //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)";
+ // CookieContainer cookieCon = new CookieContainer();
+ //
+ // // string name=cookieheader.Substring(0,cookieheader.IndexOf("="));
+ // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1);
+ // // cookieCon.Add(new Uri(url),new Cookie(name,key));
+ //
+ //
+ // req.CookieContainer = cookieCon;
+ // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0))
+ // {
+ // req.CookieContainer.SetCookies(new Uri(url),cookieheader);
+ // }
+
+
+ //为请求加入cookies
+ CookieContainer cookieCon = new CookieContainer();
+ // req.CookieContainer = cookieCon;
+ //取得cookies 集合
+ string[] ls_cookies = cookieheader.Split(';');
+ if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。
+ {
+ req.CookieContainer = cookieCon;
+ if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0))
+ {
+ req.CookieContainer.SetCookies(new Uri(url), cookieheader);
+ }
+ }
+ else
+ {
+ //如果是多个cookie 就分别加入 cookies 容器。
+ //////////////////////////////////
+ string[] ls_cookie = null;
+
+ for (int i = 0; i < ls_cookies.Length; i++)
+ {
+ ls_cookie = ls_cookies[i].Split('=');
+ // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim()));
+ cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1)));
+ }
+ req.CookieContainer = cookieCon;
+
+ ////////////////////////////////////
+ }
+
+
+
+ res = (HttpWebResponse)req.GetResponse();
+ Stream ReceiveStream = res.GetResponseStream();
+
+
+ byte[] mybytes = new byte[4096];
+
+ int count = ReceiveStream.Read(mybytes, 0, 4096);
+
+ byte[] image = new byte[count];
+
+ Array.Copy(mybytes, image, count);
+
+
+
+ if (res != null)
+ {
+ res.Close();
+ }
+ return image;
+ }
+ finally
+ {
+ }
+ }
+
+ #endregion
+
+ #region GetImage(String url,string cookieheader,out string outcookieheader,string Header_Referer)
+ ///
+ ///
+ ///
+ /// 目标url
+ /// 输入Cookie
+ ///
+ public static byte[] GetImage(String url, string cookieheader, out string outcookieheader, string Header_Referer)
+ {
+ // outcookieheader="";
+
+ HttpWebResponse res = null;
+
+
+ try
+ {
+ HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
+ if (Header_Referer.Length > 1)
+ {
+ req.Referer = Header_Referer;
+ }
+ // req.Method = "GET";
+ // req.ContentType = "application/x-www-form-urlencoded";
+ //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)";
+ // CookieContainer cookieCon = new CookieContainer();
+ //
+ // // string name=cookieheader.Substring(0,cookieheader.IndexOf("="));
+ // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1);
+ // // cookieCon.Add(new Uri(url),new Cookie(name,key));
+ //
+ //
+ // req.CookieContainer = cookieCon;
+ // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0))
+ // {
+ // req.CookieContainer.SetCookies(new Uri(url),cookieheader);
+ // }
+
+ //为请求加入cookies
+ CookieContainer cookieCon = new CookieContainer();
+ // req.CookieContainer = cookieCon;
+ //取得cookies 集合
+ string[] ls_cookies = cookieheader.Split(';');
+ if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。
+ {
+ req.CookieContainer = cookieCon;
+ if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0))
+ {
+ req.CookieContainer.SetCookies(new Uri(url), cookieheader);
+ }
+ }
+ else
+ {
+ //如果是多个cookie 就分别加入 cookies 容器。
+ //////////////////////////////////
+ string[] ls_cookie = null;
+
+ for (int i = 0; i < ls_cookies.Length; i++)
+ {
+ ls_cookie = ls_cookies[i].Split('=');
+ // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim()));
+ cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1)));
+ }
+ req.CookieContainer = cookieCon;
+
+ ////////////////////////////////////
+ }
+
+
+
+ res = (HttpWebResponse)req.GetResponse();
+ Stream ReceiveStream = res.GetResponseStream();
+
+ outcookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));//获得cookie
+
+ if (outcookieheader.Length < 2)
+ {
+ try
+ {
+ outcookieheader = res.Headers["Set-Cookie"];
+ outcookieheader = outcookieheader.Substring(0, outcookieheader.IndexOf(";"));
+ }
+ catch
+ {
+ outcookieheader = "";
+ }
+ }
+
+
+ byte[] mybytes = new byte[4096];
+
+ int count = ReceiveStream.Read(mybytes, 0, 4096);
+
+ byte[] image = new byte[count];
+
+ Array.Copy(mybytes, image, count);
+
+
+
+ if (res != null)
+ {
+ res.Close();
+ }
+ return image;
+ }
+ finally
+ {
+ }
+ }
+
+ #endregion
+
+ #region GetImage(String url,string cookieheader,string Header_Referer)
+ ///
+ ///
+ ///
+ /// 目标url
+ /// 输入Cookie
+ /// 包头 Referer
+ ///
+ public static byte[] GetImage(String url, string cookieheader, string Header_Referer)
+ {
+ // outcookieheader="";
+
+ HttpWebResponse res = null;
+
+
+ try
+ {
+ HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
+ if (Header_Referer.Length > 1)
+ {
+ req.Referer = Header_Referer;
+ }
+ // req.Method = "GET";
+ // req.ContentType = "application/x-www-form-urlencoded";
+ //req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)";
+ // CookieContainer cookieCon = new CookieContainer();
+ //
+ // // string name=cookieheader.Substring(0,cookieheader.IndexOf("="));
+ // // string key=cookieheader.Substring(cookieheader.IndexOf("=")+1,cookieheader.Length-cookieheader.IndexOf("=")-1);
+ // // cookieCon.Add(new Uri(url),new Cookie(name,key));
+ //
+ //
+ // req.CookieContainer = cookieCon;
+ // if ((cookieheader.Length>0 )&(cookieheader.IndexOf("=")>0))
+ // {
+ // req.CookieContainer.SetCookies(new Uri(url),cookieheader);
+ // }
+
+ //为请求加入cookies
+ CookieContainer cookieCon = new CookieContainer();
+ // req.CookieContainer = cookieCon;
+ //取得cookies 集合
+ string[] ls_cookies = cookieheader.Split(';');
+ if (ls_cookies.Length <= 1) //如果有一个或没有cookies 就采用下面的方法。
+ {
+ req.CookieContainer = cookieCon;
+ if ((cookieheader.Length > 0) & (cookieheader.IndexOf("=") > 0))
+ {
+ req.CookieContainer.SetCookies(new Uri(url), cookieheader);
+ }
+ }
+ else
+ {
+ //如果是多个cookie 就分别加入 cookies 容器。
+ //////////////////////////////////
+ string[] ls_cookie = null;
+
+ for (int i = 0; i < ls_cookies.Length; i++)
+ {
+ ls_cookie = ls_cookies[i].Split('=');
+ // cookieCon.Add(new Uri(url),new Cookie(ls_cookie[0].ToString().Trim(),ls_cookie[1].ToString().Trim()));
+ cookieCon.Add(new Uri(url), new Cookie(ls_cookie[0].ToString().Trim(), ls_cookies[i].Substring(ls_cookies[i].IndexOf("=") + 1)));
+ }
+ req.CookieContainer = cookieCon;
+
+ ////////////////////////////////////
+ }
+
+
+
+ res = (HttpWebResponse)req.GetResponse();
+ Stream ReceiveStream = res.GetResponseStream();
+
+
+ byte[] mybytes = new byte[4096];
+
+ int count = ReceiveStream.Read(mybytes, 0, 4096);
+
+ byte[] image = new byte[count];
+
+ Array.Copy(mybytes, image, count);
+
+
+
+ if (res != null)
+ {
+ res.Close();
+ }
+ return image;
+ }
+ finally
+ {
+ }
+ }
+
+ #endregion
+
+ #region GetImage(String url,string cookieheader,string Header_Referer,string Header_UserAgent,string http_type)
+
+ #endregion
+
+
+ #endregion
+ }
+}
diff --git a/JiLinApp/JiLinApp.csproj b/JiLinApp/JiLinApp.csproj
index 8b6341e..23f4c90 100644
--- a/JiLinApp/JiLinApp.csproj
+++ b/JiLinApp/JiLinApp.csproj
@@ -12,6 +12,9 @@
6
+
+
+