将长url转化为短url

public class ShortAddressUtil {
	private static final char[] HEX_16;
	private static final char[] HEX_62;
	private static MessageDigest digest;
	
	static{
		HEX_16 = new char[]{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
		HEX_62 = new char[62];
		int index = 0;
		for(int i = 'a'; i<'a'+26; i++,index++){
			HEX_62[index] = (char)i;
		}
		for(int i = '0'; i<'0'+10; i++,index++){
			HEX_62[index] = (char)i;
		}
		for(int i = 'A'; i<'A'+26; i++,index++){
			HEX_62[index] = (char)i;
		}
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	public static String[] convertShortURL(String longURL){
		if(digest == null) return null;
		
		digest.update(longURL.getBytes());
		byte[] bs = digest.digest();
		char[] buff = new char[ bs.length * 2 ];
		for(int i=0;i<bs.length;i++){
			buff[i*2]   = HEX_16[bs[i]>>>4&0xF];
			buff[i*2+1] = HEX_16[bs[i]&0xF];
		}
		
		String[] resURL = new String[4];
		for(int i=0;i<4;i++){
			int int16 = (int) (0x3fffffff & Long.parseLong(new String(buff,i*8,8),16));
			char[] chs = new char[6];
			for(int j=0;j<6;j++){
				chs[j] = HEX_62[int16 & 0x3d];
				int16 = int16>>>5;
			}
			resURL[i] = new String(chs);
		}
		return resURL;
	}
	
	public static void main(String[] args) {
		System.out.println(Arrays.toString(convertShortURL("http://www.hao123.com/index.html?debug=true")));
	}
}

 

你可能感兴趣的:(url)