最近看到微博的短链接真是很火啊,新浪、腾讯、搜狐等微博网站都加入了短链接的功能。之所以要是使用短链接,主要是因为微博只允许发140字,如果链接地址太长的话,那么发送的字数将大大减少。短链接的主要职责就是把原始链接很长的地址压缩成只有6个字母的短链接地址,当我们点击这6个字母的链接后,我们又可以跳转到原始链接地址。
开始以为短链接是按照某种算法把原始链接压缩为短链接,再根据算法从短链接反算成原始链接的。后来尝试了下压缩算法(gzip压缩算法),发现对于url这种字符串越是压缩,长度就越长。通过对压缩算法的一些了解,发现靠压缩算法来实现这个功能不太靠谱。
后来在网上找到一个生成算法,该算法主要使用MD5算法对原始链接进行加密(这里使用的MD5加密后的字符串长度为32位),然后对加密后的字符串进行处理以得到短链接的地址。原始的算法是C#版本的,这里我把该算法修改成Java版本的.算法的具体代码如下,代码中有注释:
一、代码
packagecom.csdn.shorturl; publicclassShortUrlGenerator {
/** *@paramargs */ publicstaticvoidmain(String[] args) { //长连接:http://tech.sina.com.cn/i/2011-03-23/11285321288.shtml //新浪解析后的短链接为:http://t.cn/h1jGSC String sLongUrl ="http://tech.sina.com.cn/i/2011-03-23/11285321288.shtml";// 3BD768E58042156E54626860E241E999 String[] aResult =shortUrl(sLongUrl); //打印出结果 for(inti = 0; i < aResult.length; i++) { System.out.println("["+ i +"]:::"+ aResult[i]); } }
publicstaticString[] shortUrl(String url) { //可以自定义生成MD5加密字符传前的混合KEY String key ="wuguowei"; //要使用生成URL的字符 String[] chars =newString[] {"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 sMD5EncryptResult = (newCMyEncrypt()).getMD5OfStr(key + url); String hex = sMD5EncryptResult;
String[] resUrl =newString[4]; for(inti = 0; i < 4; i++) {
//把加密字符按照8位一组16进制与0x3FFFFFFF进行位与运算 String sTempSubString = hex.substring(i * 8, i * 8 + 8);
//这里需要使用long型来转换,因为Inteper.parseInt()只能处理31位,首位为符号位,如果不用long,则会越界 longlHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16); String outChars =""; for(intj = 0; j < 6; j++) { //把得到的值与0x0000003D进行位与运算,取得字符数组chars索引 longindex = 0x0000003D & lHexLong; //把取得的字符相加 outChars += chars[(int) index]; //每次循环按位右移5位 lHexLong = lHexLong >> 5; } //把字符串存入对应索引的输出数组 resUrl[i] = outChars; } returnresUrl; } }
|
二、输出结果
执行上面代码的结果如下,会产生4组6位字符串,任意一组都可以作为当前字符串的短链接地址。
[0]:::7nUFJn [1]:::f6Zzy2 [2]:::j6jmQb [3]:::2eAjea |
三、跳转原理
当我们生成短链接之后,只需要在表中(数据库或者NoSql)存储原始链接与短链接的映射关系即可。当我们访问短链接时,只需要从映射关系中找到原始链接,即可跳转到原始链接。
文章转载自http://blog.163.com/linfeng_0212/blog/static/622213820115281026047/