根據IP獲取國家

jackchain發表於2014-12-12

國外的還算比較權威的IP地址庫,而且免費,每天呼叫次數不超過1000免費。超過另收費。

public string Ip2Country(string ip)
        {
            try
            {
                string url = "http://api.ipinfodb.com/v3/ip-country/?key=<your key,should regist first>&ip=" + ip;
                string rst = HttpCrossDomain.Get(url,10000);
                if (rst.Split(';').Count() >= 4)
                    rst = rst.Split(';')[3];
                else
                    rst = "";
                return rst;
            }
            catch
            {
                return "ERROR";
            }
        }
/// <summary>
        /// 跨域訪問
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Get(string url, int time = 60000)
        {
            Uri address = new Uri(url);
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/json;charset=utf-8"; //"application/x-www-form-urlencoded";
            request.Timeout = time;
            string result = "";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                result = reader.ReadToEnd();
            }
            return (result);
        }

 

相關文章