生成短链接

来源:互联网 发布:淘宝怎么打假 编辑:程序博客网 时间:2024/05/21 07:05
public class ShortUrlGenerate {public static void main(String[] args) {// 长连接: http://www.kevin.com/abc.html// 生成短链接为: http://abc.cn/h1jGSCString sLongUrl = "http://www.kevin.com/abc.html";String[] aResult = shortUrl(sLongUrl);for (int i = 0; i < aResult.length; i++) {System.out.println(aResult[i]);}}private static final String sign = "8e2e2df910f844bdbcb531170c75b246";/** * 生成 URL 的字符 */private static final String[] CHARS = new String[] { "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","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",};public static String[] shortUrl(String url) {String hex = MD5Util.getMD5(sign + url);String[] resUrl = new String[4];for (int i = 0; i < resUrl.length; i++) {// 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算String str = hex.substring(i * 8, i * 8 + 8);// 这里需要使用 long 型来转换,因为Inteper.parseInt()只能处理 31 位 , 首位为符号位 ,// 如果不用long,则会越界long lHexLong = 0x3FFFFFFF & Long.parseLong(str, 16);String outChars = "";for (int j = 0; j < 6; j++) {long index = CHARS.length - 1 & lHexLong;outChars += CHARS[(int) index];lHexLong = lHexLong >> 5;}resUrl[i] = outChars;}return resUrl;}}

0 0