Java版短网址(ShortUrl)的算法

先来看看短网址映射算法的理论(网上找到的资料):

① 将长网址用md5算法生成32位签名串,分为4段,,每段8个字符;

② 对这4段循环处理,取每段的8个字符, 将他看成16进制字符串与0x3fffffff(30位1)的位与操作,超过30位的忽略处理;

③ 将每段得到的这30位又分成6段,每5位的数字作为字母表的索引取得特定字符,依次进行获得6位字符串;

④ 这样一个md5字符串可以获得4个6位串,取里面的任意一个就可作为这个长url的短url地址。

很简单的理论,我们并不一定说得到的URL是唯一的,但是我们能够取出4组URL,这样几乎不会出现太大的重复。

首先,请大家了解在Java中如何用MD5来加密字符串得到32位的加密后的字符串,下面这个链接就是我已经封装好的Java MD5算法:

http://www.cnblogs.com/solove/archive/2011/10/18/2216715.html

下面来看看程序部分:

  1. package basic; 
  2.  
  3. import util.Encript; 
  4.  
  5. public class ShortUrl { 
  6.     public static void main(String[] args) { 
  7.         String url = "http://www.sunchis.com"
  8.         for (String string : ShortText(url)) { 
  9.             print(string); 
  10.         } 
  11.     } 
  12.      
  13.     public static String[] ShortText(String string){ 
  14.         String key = "XuLiang";                 //自定义生成MD5加密字符串前的混合KEY 
  15.         String[] chars = new String[]{          //要使用生成URL的字符 
  16.             "a","b","c","d","e","f","g","h"
  17.             "i","j","k","l","m","n","o","p"
  18.             "q","r","s","t","u","v","w","x"
  19.             "y","z","0","1","2","3","4","5"
  20.             "6","7","8","9","A","B","C","D"
  21.             "E","F","G","H","I","J","K","L"
  22.             "M","N","O","P","Q","R","S","T"
  23.             "U","V","W","X","Y","Z" 
  24.         }; 
  25.          
  26.         String hex = Encript.md5(key + string); 
  27.         int hexLen = hex.length(); 
  28.         int subHexLen = hexLen / 8
  29.         String[] ShortStr = new String[4]; 
  30.          
  31.         for (int i = 0; i < subHexLen; i++) { 
  32.             String outChars = ""
  33.             int j = i + 1
  34.             String subHex = hex.substring(i * 8, j * 8); 
  35.             long idx = Long.valueOf("3FFFFFFF"16) & Long.valueOf(subHex, 16); 
  36.              
  37.             for (int k = 0; k < 6; k++) { 
  38.                 int index = (int) (Long.valueOf("0000003D"16) & idx); 
  39.                 outChars += chars[index]; 
  40.                 idx = idx >> 5
  41.             } 
  42.             ShortStr[i] = outChars; 
  43.         } 
  44.          
  45.         return ShortStr; 
  46.     } 
  47.      
  48.     private static void print(Object messagr){ 
  49.         System.out.println(messagr); 
  50.     } 

现在可以直接使用ShortText(url)方法,可以等到下面四组值:

  1. ShortText("http://www.sunchis.com")[0];  //得到值:Jzyqma 
  2. ShortText("http://www.sunchis.com")[1];  //得到值:QBrMzm 
  3. ShortText("http://www.sunchis.com")[2];  //得到值:bQreM3 
  4. ShortText("http://www.sunchis.com")[3];  //得到值:VNBRna 
posted @ 2011-10-18 17:25  蝌蚪归来  阅读(1983)  评论(0编辑  收藏  举报