Created
August 1, 2012 09:02
-
-
Save charleehu/3225229 to your computer and use it in GitHub Desktop.
Short url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.UnsupportedEncodingException; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
/** | |
* | |
* @author <a href="mailto:[email protected]">Xiaowei Hu</a> | |
* @version 1.0 2012-8-1 下午03:17:19 | |
* @since 1.0 | |
*/ | |
public class ShortUrlUtil { | |
private static final char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', | |
'b', 'c', 'd', 'e', 'f' }; | |
private static final char[] shortChar = { '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' }; | |
/** | |
* | |
* <pre> | |
* 1)将长网址md5生成32字符签名串,分为4段, 每段8个字符; | |
* 2)对这四段循环处理, 将他看成16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理; | |
* 3)这30位分成6段,每5位的数字作为字母表的索引取得特定字符, 依次进行获得6位字符串; | |
* 4)总的md5串可以获得4个6位串;取里面的任意一个就可作为这个长url的短url地址; | |
* </pre> | |
* | |
* @param src | |
* @return | |
*/ | |
public static String[] shortUrl(String src) { | |
String md5v = md5(src); | |
String[] rs = new String[4]; | |
for (int i = 0; i < 4; i++) { | |
StringBuilder res = new StringBuilder(); | |
long hexInt = Long.parseLong(md5v.substring(i * 8, i * 8 + 8), 16) & 0x3fffffff; | |
for (int j = 0; j < 6; j++) { | |
res.append(shortChar[(int) (0x000000000000001F & hexInt)]); | |
hexInt = hexInt >> 5; | |
} | |
rs[i] = res.toString(); | |
} | |
return rs; | |
} | |
public static String md5(String src) { | |
String result = null; | |
try { | |
MessageDigest md = MessageDigest.getInstance("MD5"); | |
byte[] byd = md.digest(src.getBytes("utf-8")); | |
result = bytes2Hex(byd); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
return result; | |
} | |
private static String bytes2Hex(byte[] byd) { | |
StringBuilder s = new StringBuilder(); | |
for (byte bt : byd) { | |
char charA = hexChar[(bt >> 4) & 0x0f]; | |
char charB = hexChar[bt & 0x0f]; | |
s.append(charA).append(charB); | |
} | |
return s.toString(); | |
} | |
public static void main(String[] args) { | |
String[] ss = shortUrl("11"); | |
for (String s : ss) { | |
System.out.println(s); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment