IP地址查詢API的C#實現

Mafly發表於2015-05-14

一切從登入記錄開始

看到TX的登入記錄之後,突然想去在登入環節也加上這個功能,然後就寫了下面的具體實現程式碼。現在一點也不糾結IP在資料庫中儲存型別是UNSIGNED INT還是VARCHAR了。

乾貨來了哦^_^

using System.Net;
using System.Web;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    public class IPToLocation
    {
        public IPLocation GetLocationByTB(string ip)
        {
            if (string.IsNullOrEmpty(ip))
                return null;
            var webClient = new WebClient();
            var entity = webClient.DownloadString(string.Format("http://ip.taobao.com/service/getIpInfo.php?ip={0}",ip));
            var json = new JavaScriptSerializer().Deserialize<dynamic>(entity);
            if (json == null || json["code"] == 1)
                return GetLocationBySina(ip);    //呼叫其它介面
            var data = new JavaScriptSerializer().Serialize(json["data"]);
            IPLocation model = JsonConvert.DeserializeObject<IPLocation>(data);
            return model;
        }

        public IPLocation GetLocationBySina(string ip)
        {
            // http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={0}
            // 其它同上哦.
        }
    }

    [JsonObject]
    public class IPLocation
    {
        [JsonProperty]
        public string IP { get; set; }
        [JsonProperty]
        public string Country { get; set; }
        [JsonProperty]
        public string Country_Id { get; set; }
        [JsonProperty]
        public string Area { get; set; }
        [JsonProperty]
        ...
        ...
    }
}

原始碼下載

相關文章