首页 > 编程 > C# > 正文

C#实现类似新浪微博长URL转短地址的方法

2020-01-24 01:55:08
字体:
来源:转载
供稿:网友

本文实例讲述了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#程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表