c#根据ip获取城市地址

用的API是百度、新浪、淘宝:

1、首先是一个检测获取的值是不是中文的方法,因为有的ip只能识别出来某省,而城市名称则为空返回的json里会出现null或undefined。

 

1 public static bool HasChinese(string str)
2     {
3         return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
4     }

百度的API

/// <summary>
    /// 百度api
    /// </summary>
    /// <returns></returns>
    public static string GetBaiduIp(string ip)
    {
        try
        {
            string cs = "";
            string url = "http://api.map.baidu.com/location/ip?ak=GlfVlFKSc6Y7aSr73IHM3lQI&ip=" + ip;
            WebClient client = new WebClient();
            var buffer = client.DownloadData(url);
            string jsonText = Encoding.UTF8.GetString(buffer);
            JObject jo = JObject.Parse(jsonText);
            var txt = jo["content"]["address_detail"]["city"];
            JToken st = txt;
            string str = st.ToString();
            if (str == "")
            {
                cs = GetCS(ip);
                return cs;

            }
            int s = str.IndexOf('');
            string css = str.Substring(0, s);
            bool bl = HasChinese(css);

            if (bl)
            {
                cs = css;
            }
            else
            {
                cs = GetCS(ip);
            }

            return cs;
        }
        catch
        {
            return GetIPCitys(ip);
        }

    }

新浪API(这个是直接获取网页源代码,然后抓取)

 1  /// <summary>
 2     /// 新浪api
 3     /// </summary>
 4     /// <param name="ip"></param>
 5     /// <returns></returns>
 6 public static string GetCS(string ip)
 7     {
 8         try { 
 9         string url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=" + ip;
10         WebClient MyWebClient = new WebClient();
11         MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
12         Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
13         string stt = Encoding.GetEncoding("GBK").GetString(pageData).Trim();
14         return stt.Substring(stt.Length - 2, 2);
15         }
16         catch
17         {
18             return "未知";
19         }
20 
21     }

淘宝API

 1 /// <summary>
 2     /// 淘宝api
 3     /// </summary>
 4     /// <param name="strIP"></param>
 5     /// <returns></returns>
 6     public static string GetIPCitys(string strIP)
 7     {
 8         try
 9         {
10             string Url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + strIP + "";
11 
12             System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
13             wReq.Timeout = 2000;
14             System.Net.WebResponse wResp = wReq.GetResponse();
15             System.IO.Stream respStream = wResp.GetResponseStream();
16             using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream))
17             {
18                 string jsonText = reader.ReadToEnd();
19                 JObject ja = (JObject)JsonConvert.DeserializeObject(jsonText);
20                 if (ja["code"].ToString() == "0")
21                 {
22                     string c = ja["data"]["city"].ToString();
23                     int ci = c.IndexOf('');
24                     if (ci != -1)
25                     {
26                         c = c.Remove(ci, 1);
27                     }
28                     return c;
29                 }
30                 else
31                 {
32                     return "未知";
33                 }
34             }
35         }
36         catch (Exception)
37         {
38             return ("未知");
39         }
40     }

 

posted @ 2015-12-31 15:59  满猪小星小猪满  阅读(5650)  评论(2编辑  收藏  举报