新浪微博 ID與MID互轉 (62進制)

最近在做相和新浪微博相關的項目,因爲抓取回來的微博JOSN中,ID和MID都是一樣的。而客戶又要求可以打開單條微博的查看頁面。

本來SDK中是有QueryMID的功能的,但苦於調用次數的限制(一小時100下好像),而微博卻又是海量的(其實就幾千條啦)。

(http://weibo.com/2121718653/yvsAefokR  <-- 這個就是傳說中的MID

在網上搜了好一會,只看到URL轉ID的,沒看到ID轉URL的,實在無奈之下,只好自己寫了一個。

參考了某網友的一篇文章:http://www.cnblogs.com/beijia/archive/2011/11/22/62ToInt.html

照着修修補補,寫了這樣一個類,其中除了原作者的MID轉ID外,還可以ID轉MID。(奇怪爲啥沒人有這樣的需求呢?搜不到?)

不廢話了,馬上看代碼,複製了隨便用哈。

    public class WeiboHelper
    {
        private static String str62keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        public static String IntToEnode62(Int64 int10)
        {
            string s62 = "";
            int r = 0;
            while (int10 != 0) {
                r = Convert.ToInt32(int10 % 62);
                s62 = str62keys[r] + s62;
                int10 = (Int64)Math.Floor(int10 / 62.0);
            }
            return s62;
        }

        public static Int64 Encode62ToInt(String str62)
        {
            Int64 i10 = 0;
            for (var i = 0; i < str62.Length; i++)
            {
                double n = str62.Length - i - 1;
                i10 += Convert.ToInt64(str62keys.IndexOf(str62[i]) * Math.Pow(62, n));
            }
            return i10;
        }

        public static string Mid2Id(string str62) //yvr29p8dG
        {
            String id = "";
            for (int i = str62.Length - 4; i > -4; i = i - 4) //從最後往前以4字節爲一組讀取字符
            {
                int offset = i < 0 ? 0 : i;
                int len = i < 0 ? str62.Length % 4 : 4;
                String str = Encode62ToInt(str62.Substring(offset, len)).ToString();

                if (offset > 0) str = str.PadLeft(7, '0'); //若不是第一組,則不足7位補0

                id = str + id;
            }
            return id;
        }

        public static string Id2Mid(string str10) //3474920895989800
        {
            string mid = "";
            for (int i = str10.Length - 7; i > -7; i = i - 7) //從最後往前以7字節爲一組讀取字符
            {
                int offset = i < 0 ? 0 : i;
                int len = i < 0 ? str10.Length % 7 : 7;
                var str = IntToEnode62(Convert.ToInt64(str10.Substring(offset, len)));
                mid = str + mid;
            }
            return mid;
        }
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章