Java版短網址(ShortUrl)的算法

1:Java版短網址(ShortUrl)的算法
/** Java版短網址(ShortUrl)的算法

1.  將長網址用md5算法生成32位簽名串,分爲4段,,每段8個字符。

2.  對這4段循環處理,取每段的8個字符, 將他看成16進制字符串與0x3fffffff(30位1)的位與操作,超過30位的忽略處理。多了也沒用因爲下面要分成6段  嘿嘿正好取整。注意用Long型變量(長度問題  你懂得) 
3.  將每段得到的30位字符(後臺以long十進制顯示)又分成6段,通過移位運算將每5位分別與字符數組求與運算(0x0000003D),得到其在字符數組中的索引並取出拼串。
4.  這樣一個md5字符串可以獲得4個6位串,取裏面的任意一個就可作爲這個長url的短url地址。
跳轉原理:當我們生成短鏈接之後,只需要在表中(數據庫或者NoSql )存儲原始鏈接與短鏈接的映射關係即可。當我們訪問短鏈接時,只需要從映射關係中找到原始鏈接,即可跳轉到原始鏈接。
eg:http://6du.in/0W13as
備註(六度網址:http://www.6du.in/)
*/
package com.youngsun.lbt;

publicclass ShortUrlGenerator {
    publicstaticvoid main(String[] args) {
       // 長連接: http://www.young-sun.com
// 新浪解析後的短鏈接爲: http://***/Nvqqem
       String sLongUrl = "http://www.young-sun.com" ; // 3BD768E58042156E54626860E241E999
       String[] aResult = shortUrl (sLongUrl);
       // 打印出結果
       for ( int i = 0; i < aResult. length ; i++) { 
           System. out .println( "The string [" + i + "] is " + aResult[i]);
       } 
    } 
    publicstatic String[] shortUrl(String url) {
       // 可以自定義生成 MD5 加密字符傳前的混合 KEY
       String key = "libotao" ;
       // 要使用生成 URL 的字符
       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" , "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" 
       };
       // 對傳入網址進行 MD5 加密
       String sMD5EncryptResult = (Encript.md5(key + url));
       String hex = sMD5EncryptResult;
       String[] resUrl = new String[4]; 
       //得到 4組短鏈接字符串  
       for ( int i = 0; i < 4; i++) {
           // 把加密字符按照 8 位一組 16 進制與 0x3FFFFFFF 進行位與運算
           String sTempSubString = hex.substring(i * 8, i * 8 + 8);
           // 這裏需要使用 long 型來轉換,因爲 Inteper .parseInt() 只能處理 31 位 , 首位爲符號位 , 如果不用 long ,則會越界
           long lHexLong = 0x3FFFFFFF & Long.parseLong (sTempSubString, 16);
           String outChars = "" ;
           //循環獲得每組6位的字符串
           for ( int j = 0; j < 6; j++) {
           // 把得到的值與 0x0000003D 進行位與運算,取得字符數組 chars 索引
//(具體需要看chars數組的長度   以防下標溢出,注意起點爲0)
              long index = 0x0000003D & lHexLong;
              // 把取得的字符相加
              outChars += chars[( int ) index];
              // 每次循環按位右移 5 位
              lHexLong = lHexLong >> 5;
           }
           // 把字符串存入對應索引的輸出數組
           resUrl[i] = outChars;
       }
       return resUrl;
    }
}

2:Java調用百度短網址api

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * java調用百度短網址api
 */
public class GenerateShortUrlUtil {
    public static DefaultHttpClient httpclient;
    static {
        httpclient = new DefaultHttpClient();
        //httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何證書的瀏覽器客戶端
    }

    /**
     * 生成短網址
     * @param url 長網址
     */
    public static String  generateShortUrl(String url) {
        try {
            HttpPost httpost = new HttpPost("http://dwz.cn/create.php");
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("url", url)); // 用戶名稱
            httpost.setEntity(new UrlEncodedFormEntity(params,  "utf-8"));
            HttpResponse response = httpclient.execute(httpost);
            String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(jsonStr);
            JSONObject object = JSON.parseObject(jsonStr);
            System.out.println(object.getString("tinyurl"));
            return object.getString("tinyurl");
        } catch (Exception e) {
            e.printStackTrace();
            return "Error";
        }
    }

    public static void main(String []args){
        generateShortUrl("http://www.jb51.net/article/51881.htm");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章