using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Script.Serialization; namespace MyCode.Project.Infrastructure.Common { public class ResponseMessage { #region 接收的类型 /// /// 接收文本 /// /// /// /// /// public static string GetText(string FromUserName, string ToUserName, string Content) { CommonMethod.WriteTxt(Content);//接收的文本消息 string XML = ""; switch (Content) { case "关键字": XML = ReText(FromUserName, ToUserName, "关键词回复测试"); break; case "关注成功": XML = ReText(FromUserName, ToUserName, "自定义文字关注成功"); break; case "单图文": XML = ReArticle(FromUserName, ToUserName, "测试标题", "测试详情——百度搜索链接", "http://pic.cnblogs.com/avatar/743013/20150521120816.png", "http://www.baidu.com"); break; default: XML = ReText(FromUserName, ToUserName, "无对应关键字"); break; } return XML; } /// /// 未关注扫描带参数二维码 /// /// /// /// 参数值 /// public static string SubScanQrcode(string FromUserName, string ToUserName, string EventKey) { string result = MyCode.Project.Infrastructure.Common.ResponseMessage.ReText(FromUserName, ToUserName, "未关注扫描带参数二维码:"+ EventKey); return result; } /// /// 已关注扫描带参数二维码 /// /// /// /// 参数值 /// public static string ScanQrcode(string FromUserName, string ToUserName, string EventKey) { string result= MyCode.Project.Infrastructure.Common.ResponseMessage.ReText(FromUserName, ToUserName, EventKey); return result; } #endregion #region 回复方式 /// /// 回复文本 /// /// 发送给谁(openid) /// 来自谁(公众账号ID) /// 回复类型文本 /// 拼凑的XML public static string ReText(string FromUserName, string ToUserName, string Content) { string XML = "";//发送给谁(openid),来自谁(公众账号ID) XML += "" + CommonMethod.ConvertDateTimeInt(DateTime.Now) + "";//回复时间戳 XML += "";//回复类型文本 XML += "0";//回复内容 FuncFlag设置为1的时候,自动星标刚才接收到的消息,适合活动统计使用 return XML; } /// /// 回复单图文 /// /// 发送给谁(openid) /// 来自谁(公众账号ID) /// 标题 /// 详情 /// 图片地址 /// 地址 /// 拼凑的XML public static string ReArticle(string FromUserName, string ToUserName, string Title, string Description, string PicUrl, string Url) { string XML = "";//发送给谁(openid),来自谁(公众账号ID) XML += "" + CommonMethod.ConvertDateTimeInt(DateTime.Now) + "";//回复时间戳 XML += "1"; XML += "<![CDATA[" + Title + "]]>"; XML += "0"; return XML; } /// /// 多图文回复 /// /// 发送给谁(openid) /// 来自谁(公众账号ID) /// 图文数量 /// /// public static string ReArticle(string FromUserName, string ToUserName, int ArticleCount, System.Data.DataTable dtArticle) { string XML = "";//发送给谁(openid),来自谁(公众账号ID) XML += "" + CommonMethod.ConvertDateTimeInt(DateTime.Now) + "";//回复时间戳 XML += "" + ArticleCount + ""; foreach (System.Data.DataRow Item in dtArticle.Rows) { XML += "<![CDATA[" + Item["Title"] + "]]>"; } XML += "0"; return XML; } #endregion } /// /// 通用方法类 /// public class CommonMethod { #region Post/Get提交调用抓取 /// /// Post/get 提交调用抓取 /// /// 提交地址 /// 参数 /// string public static string WebRequestPostOrGet(string sUrl, string sParam) { byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam); Uri uriurl = new Uri(sUrl); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param); req.Method = "Post"; req.Timeout = 120 * 1000; req.ContentType = "application/x-www-form-urlencoded;"; req.ContentLength = bt.Length; using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存 { reqStream.Write(bt, 0, bt.Length); reqStream.Flush(); } try { using (WebResponse res = req.GetResponse()) { //在这里对接收到的页面内容进行处理 Stream resStream = res.GetResponseStream(); StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8); string resLine; System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder(); while ((resLine = resStreamReader.ReadLine()) != null) { resStringBuilder.Append(resLine + System.Environment.NewLine); } resStream.Close(); resStreamReader.Close(); return resStringBuilder.ToString(); } } catch (Exception ex) { return ex.Message;//url错误时候回报错 } } #endregion Post/Get提交调用抓取 #region unix/datatime 时间转换 /// /// unix时间转换为datetime /// /// /// public static DateTime UnixTimeToTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } /// /// datetime转换为unixtime /// /// /// public static int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } #endregion #region 记录bug,以便调试 /// /// 记录bug,以便调试 /// public static bool WriteTxt(string str) { try { string LogPath = HttpContext.Current.Server.MapPath("/err_log/"); if (!Directory.Exists(LogPath)) { Directory.CreateDirectory(LogPath); } FileStream FileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("/err_log//xiejun_" + DateTime.Now.ToLongDateString() + "_.txt"), FileMode.Append); StreamWriter StreamWriter = new StreamWriter(FileStream); //开始写入 StreamWriter.WriteLine(str); //清空缓冲区 StreamWriter.Flush(); //关闭流 StreamWriter.Close(); FileStream.Close(); } catch (Exception) { return false; } return true; } #endregion #region 生成随机字符 /// /// 生成随机字符 /// /// 生成字符串的长度 /// 返回随机字符串 public static string GetRandCode(int iLength) { string sCode = ""; if (iLength == 0) { iLength = 4; } string codeSerial = "0,1,2,3,4,5,6,7,8,9,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"; string[] arr = codeSerial.Split(','); int randValue = -1; Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < iLength; i++) { randValue = rand.Next(0, arr.Length - 1); sCode += arr[randValue]; } return sCode; } #endregion #region 根据ip获取地点 /// 获取Ip归属地 /// /// ip /// 归属地 public static string GetIpAddress(string ip) { JavaScriptSerializer Jss = new JavaScriptSerializer(); //http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.192.3.42 调用新浪的接口 string address = string.Empty; try { string reText = WebRequestPostOrGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip, ""); Dictionary DicText = (Dictionary)Jss.DeserializeObject(reText); address = DicText["city"].ToString(); WriteTxt("city:" + address); } catch { } return address; } #endregion } }