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
下面来看看程序部分:
- package basic;
- import util.Encript;
- public class ShortUrl {
- public static void main(String[] args) {
- String url = "http://www.sunchis.com";
- for (String string : ShortText(url)) {
- print(string);
- }
- }
- public static String[] ShortText(String string){
- String key = "XuLiang"; //自定义生成MD5加密字符串前的混合KEY
- String[] chars = new String[]{ //要使用生成URL的字符
- "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"
- };
- String hex = Encript.md5(key + string);
- int hexLen = hex.length();
- int subHexLen = hexLen / 8;
- String[] ShortStr = new String[4];
- for (int i = 0; i < subHexLen; i++) {
- String outChars = "";
- int j = i + 1;
- String subHex = hex.substring(i * 8, j * 8);
- long idx = Long.valueOf("3FFFFFFF", 16) & Long.valueOf(subHex, 16);
- for (int k = 0; k < 6; k++) {
- int index = (int) (Long.valueOf("0000003D", 16) & idx);
- outChars += chars[index];
- idx = idx >> 5;
- }
- ShortStr[i] = outChars;
- }
- return ShortStr;
- }
- private static void print(Object messagr){
- System.out.println(messagr);
- }
- }
现在可以直接使用ShortText(url)方法,可以等到下面四组值:
- ShortText("http://www.sunchis.com")[0]; //得到值:Jzyqma
- ShortText("http://www.sunchis.com")[1]; //得到值:QBrMzm
- ShortText("http://www.sunchis.com")[2]; //得到值:bQreM3
- ShortText("http://www.sunchis.com")[3]; //得到值:VNBRna