10、長鏈接轉短鏈接


1、概述

短網址的好處眾多,便於記憶,占用字符少等,現在市面上出現了眾多的將長網址轉變為短網址的方法,但是由於他們都是小的公司在幕后運營,所以很不靠譜,面對隨時關閉服務的可能,這樣也導致我們將轉換好了的短網址也會失效失鏈!那么怎樣才能使轉換好了的短網址永久有效呢?

2、利用微信公眾號接口實現長鏈接轉短鏈接

開發者用於生成二維碼的原鏈接(商品、支付二維碼等)太長導致掃碼速度和成功率下降,將原長鏈接通過此接口轉成短鏈接再生成二維碼將大大提升掃碼速度和成功率。微信公眾號平台提供的長鏈接轉短鏈接接口是:

http請求方式: POST
https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN

參數說明

參數 是否必須 說明
access_token 調用接口憑證
action 此處填long2short,代表長鏈接轉短鏈接
long_url 需要轉換的長鏈接,支持http://、https://、weixin://wxpay 格式的url

調用舉例

curl -d "{\"action\":\"long2short\",\"long_url\":\"http://wap.koudaitong.com/v2/showcase/goods?alias=128wi9shh&spm=h56083&redirect_count=1\"}" "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN"

返回說明,正常情況下,微信會返回下述JSON數據包給公眾號:

{"errcode":0,"errmsg":"ok","short_url":"http:\/\/w.url.cn\/s\/AvCo6Ih"}

代碼參考

/// <summary> /// 長鏈接轉短鏈接 /// </summary> /// <param name="longUrl">長鏈接</param> /// <returns></returns> [HttpPost] [ValidateInput(false)] [LoginAuthorize] public ActionResult GetShortUrl(string longUrl) { WeixinOfficialAccountEntity currentWeixinOfficialAccountEntity = RDIFrameworkService.Instance.WeixinBasicService.GetCurrentOfficialAccountEntity(ManageProvider.Provider.Current()); string token = currentWeixinOfficialAccountEntity.AccessToken; //微信請求地址 string url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" + token; //請求的json參數 string data = "{\"action\":\"long2short\",\"long_url\":\"" + longUrl + "\"}"; string ret = string.Empty; try { byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(data); //轉化 HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url)); webReq.Method = "POST"; webReq.ContentType = "application/json"; webReq.ContentLength = byteArray.Length; Stream newStream = webReq.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length);//寫入參數 newStream.Close(); HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); var ce = response.ContentEncoding; StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8")); ret = sr.ReadToEnd(); sr.Close(); response.Close(); newStream.Close(); } catch (Exception ex) { } //正常情況下,微信會返回下述JSON數據包給公眾號: //{"errcode":0,"errmsg":"ok","short_url":"http:\/\/w.url.cn\/s\/AvCo6Ih"} string errcode = "";//錯誤碼。 string errmsg = "";//錯誤信息。 string short_url = "";//短鏈接。 //解析響應信息 if (!string.IsNullOrWhiteSpace(ret)) { JObject jo = (JObject)JsonConvert.DeserializeObject(ret); errcode = jo["errcode"].ToString();//錯誤碼。 errmsg = jo["errmsg"].ToString();//錯誤信息。 short_url = jo["short_url"].ToString();//短鏈接。 } return Content(new JsonMessage { Success = true, Data = short_url, Type = ResultType.Success, Message = errmsg }.ToString()); }

3、使用效果參考

長鏈接轉短鏈接界面


生成的短鏈接效果

上面的界面我們把鏈接地址http://blog.rdiframework.net/article/190通過我們提供的長鏈接轉短鏈接界面功能轉成了短鏈接https://w.url.cn/s/ALO1xZC


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM