本文實例講述了C#實現類似新浪微博長URL轉短地址的方法。分享給大家供大家參考。具體如下:
一、前臺判斷用戶輸入URL的JS代碼如下。
function CheckInput() { var $txtLength = $("#inp_text").val().length; if ($txtLength > 10) { var url = $("#inp_text").val(); var xx = url.match(RegExp("((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(//.[-A-Za-z0-9]+)*(//.[-A-Za-z]{2,5}))|([0-9]{1,3}(//.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_//$//.//+//!//*//(//),;:@&=//?/~//#//%]*)*", "gi") || []); if (xx != null) { for (var i = 0; i < xx.length; i++) { var $txtLength = $("#inp_text").val().length; $txtLength = $txtLength - xx[i].length + 11; } } } if ($txtLength < 141) { $("#div_txtlength").html("還能輸入<span>" + (140 - $txtLength) + "</span>個字"); } else { $("#div_txtlength").html("超出<span>" + ($txtLength - 140) + "</span>個字"); } } function InsertText() { if ($("#inp_text").val().Trim().length == 0) { art.dialog({ title: '錯誤', icon: 'error', content: '請輸入內容', width: "150px", height: "80px", lock: true }); return; } //長url轉換成短url var url = $("#inp_text").val(); var xx = url.match(RegExp("((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(//.[-A-Za-z0-9]+)*(//.[-A-Za-z]{2,5}))|([0-9]{1,3}(//.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_//$//.//+//!//*//(//),;:@&=//?/~//#//%]*)*", "gi") || []); var $txtLength = $("#inp_text").val().length; if (xx != null) { for (var i = 0; i < xx.length; i++) { $txtLength = $txtLength - xx[i].length + 11; } } if ($txtLength < 141) { $("#div_txtlength").html("還能輸入<span>" + (140 - $txtLength) + "</span>個字"); } else { $("#div_txtlength").html("超出<span>" + ($txtLength - 140) + "</span>個字"); } if ($txtLength > 140) { art.dialog({ title: '錯誤', icon: 'error', content: '字數超出限制', width: "150px", height: "80px", lock: true }); return false; } $.ajax({ type: "POST", url: "../MiniBlog/Handler.ashx", data: { "txt": $("#inp_text").val() }, datatype: "html", beforeSend: function () { $("#div_txtlength").html("正在提交。。。"); }, success: function (data) { if (data.length > 1) { window.location.reload(); } else { art.dialog({ title: '錯誤', icon: 'error', content: '發布失敗,請復制內容后刷新當前頁面。', width: "150px", height: "80px", lock: true }); } }, complete: function (XMLHttpRequest, textStatus) { // alert(XMLHttpRequest.responseText); // alert(textStatus); }, error: function () { } }); }
二、前臺ASPX的代碼如下(部分)
<div class="title_left"> 有什么新鮮事和大家分享?</div> <div class="left_box"> <textarea class="textarea01" id="inp_text" onblur="CheckInput()" onkeyup="CheckInput()"></textarea></div> <div class="left_box"> <div class="insert" style="visibility: hidden"> <ul> <li style="background: url(../images/weibo/icon.jpg) no-repeat -172px 0px;"><a href="#"> 表情</a></li> <li style="background: url(../images/weibo/icon.jpg) no-repeat -115px 0px;"><a href="#"> 圖片</a></li> <li style="background: url(../images/weibo/icon.jpg) no-repeat -229px 0px;"><a href="#"> 音樂</a></li> </ul> </div> <div class="Prompt" id="div_txtlength"> 還能輸入<span>140</span>字</div> <div class="bottom_gb"> <a href="javascript:void(0)" onclick="InsertText();" class="link1"></a> </div> </div>
三、以上是用來判斷用戶輸入內容里面是否含有網址,下面是后臺提交到數據庫的時候進行的轉換
#region 長url轉短url Regex rx = new Regex("((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(//.[-A-Za-z0-9]+)*(//.[-A-Za-z]{2,5}))|([0-9]{1,3}(//.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_//$//.//+//!//*//(//),;:@&=//?/~//#//%]*)*", RegexOptions.IgnoreCase); string txt_context = context.Request.Form["txt"].ToString(); MatchCollection mc = rx.Matches(txt_context); if (mc.Count > 0) { for (int i = 0; i < mc.Count; i++) { Haedu.Gxt.Model.MINIBLOGURL_Model M_url = new Haedu.Gxt.Model.MINIBLOGURL_Model(); Haedu.Gxt.Bll.MINIBLOGURL B_url = new Haedu.Gxt.Bll.MINIBLOGURL(); M_url.BACKUP1 = Common.md5(mc[i].Value); M_url.BACKUP2 = " "; M_url.CREATETIME = DateTime.Now; M_url.CREATEUSER = User_BaseInfo.GetUserID; M_url.ID = Common.GetGUID; M_url.STATE = 0; M_url.SURL = mc[0].Value; M_url.TURL = MiniBlog.ShortUrl(mc[i].Value); txt_context = txt_context.Replace(mc[i].Value, M_url.TURL); if(!B_url.Exists(M_url.BACKUP1)) { B_url.Add(M_url); } } } #endregion #region 寫入微博數據庫 --寫入微博數據庫的代碼 #endregion
四、MiniBlog.ShortUrl方法代碼
#region 長轉短url /// <summary> /// 長url轉短url /// </summary> /// <param name="url">原url</param> /// <returns>返回短url</returns> public static string ShortUrl(string url) { //可以自定義生成MD5加密字符傳前的混合KEY string key = "Haedu_MiniBlog"; //要使用生成URL的字符 string[] chars = new string[]{ "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","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"}; //對傳入網址進行MD5加密 string hex = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key + url, "md5"); string[] resUrl = new string[4]; for (int i = 0; i < 4; i++) { //把加密字符按照8位一組16進制與0x3FFFFFFF進行位與運算 int hexint = 0x3FFFFFFF & Convert.ToInt32("0x" + hex.Substring(i * 8, 8), 16); string outChars = string.Empty; for (int j = 0; j < 6; j++) { //把得到的值與0x0000003D進行位與運算,取得字符數組chars索引 int index = 0x0000003D & hexint; //把取得的字符相加 outChars += chars[index]; //每次循環按位右移5位 hexint = hexint >> 5; } //把字符串存入對應索引的輸出數組 resUrl[i] = outChars; } return "http://url.cn/" + resUrl[(new Random()).Next(0, 3)]; } #endregion
五、短URL轉換成原始URL
#region 短url替換成原始url public static string CheckUrl(string context) { Regex rx = new Regex("((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(//.[-A-Za-z0-9]+)*(//.[-A-Za-z]{2,5}))|([0-9]{1,3}(//.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_//$//.//+//!//*//(//),;:@&=//?/~//#//%]*)*", RegexOptions.IgnoreCase); MatchCollection mc = rx.Matches(context); if (mc.Count > 0) { for (int i = 0; i < mc.Count; i++) { Haedu.Gxt.Model.MINIBLOGURL_Model M_url = new Haedu.Gxt.Model.MINIBLOGURL_Model(); Haedu.Gxt.Bll.MINIBLOGURL B_url = new Haedu.Gxt.Bll.MINIBLOGURL(); M_url = B_url.GetModel(mc[i].Value); if (M_url != null) { if (int.Parse(M_url.STATE.ToString()) == 2) { context = context.Replace(mc[i].Value, "鏈接已經被屏蔽"); } else { context = context.Replace(mc[i].Value, "<a href=/"" + M_url.SURL + "/" target=/"_blank/" title=/"" + M_url.SURL + "/" >" + mc[i].Value + "</a>"); } } } } return context; } #endregion
六、數據庫結構(oracle)
-- Create table create table MINIBLOGURL ( id VARCHAR2(50) not null, surl VARCHAR2(200) not null, turl VARCHAR2(100) not null, createtime DATE not null, createuser VARCHAR2(50) not null, state NUMBER(1) not null, backup1 VARCHAR2(200) not null, backup2 VARCHAR2(200) not null ) tablespace TAB_GXT pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 8K minextents 1 maxextents unlimited ); -- Add comments to the columns comment on column MINIBLOGURL.id is '邏輯ID'; comment on column MINIBLOGURL.surl is '原始url'; comment on column MINIBLOGURL.turl is '轉成的短url'; comment on column MINIBLOGURL.createtime is '創建時間'; comment on column MINIBLOGURL.createuser is '創建人ID'; comment on column MINIBLOGURL.state is '狀態,0為認證的網址(比較知名的網站域名),1為未認證的網址(小網站),2為鎖定不允許點擊(廣告類的網址)'; comment on column MINIBLOGURL.backup1 is 'MD5值,用來比較網址是否已經存在'; comment on column MINIBLOGURL.backup2 is '備用字段2'; -- Create/Recreate primary, unique and foreign key constraints alter table MINIBLOGURL add constraint PK_ID primary key (ID) using index tablespace TAB_GXT pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); -- Create/Recreate indexes create index IX_CREATEUSER on MINIBLOGURL (CREATEUSER) tablespace TAB_GXT pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create unique index IX_MD5 on MINIBLOGURL (BACKUP1) tablespace TAB_GXT pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create index IX_SURL on MINIBLOGURL (SURL) tablespace TAB_GXT pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create index IX_TURL on MINIBLOGURL (TURL) tablespace TAB_GXT pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited );
至此,基于上面的代碼即可完成微博的長短URL相互轉換,具體應用的時候還需要自己進行調整修改。
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答