根据Ip获取城市帮助类

思路构建

1.先通过本地的测IP地址库进行匹配

2.如果本地IP地址库存在此IP的城市信息,就直接返回,调用速度也快

3.如果本地没有对应的IP城市信息,必须通过调用网络的IP查询的API了,这里我使用了(百度,新浪,和淘宝)

注意:百度的调用不是很正常,大批量调用

 要引用dll Newtonsoft.Json.dll
 下载地址:http://www.newtonsoft.com/products/json/
 1.解压下载文件,得到Newtonsoft.Json.dll   2.在项目中添加引用..3.兼容.net framwork2.0到4.5框架

使用NewtonSoft.JSON.dll来序列化和发序列化对象

1        #region 调用百度  新浪和淘宝接口返回地址   1.百度 2.新浪 3.淘宝
2         /// <summary>
3         /// 调用百度  新浪和淘宝接口返回地址   1.百度 2.新浪 3.淘宝
4         /// </summary>
5         /// <param name="Serve">1.百度 2.新浪 3.淘宝</param>
6         /// <param name="ipAddress"></param>
7         /// <returns></returns>
8         public string GetAddress(int Serve, string ipAddress)
9         {
10             try
11             {
12                 var match =
13                     new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))");
14                 if (!match.IsMatch(ipAddress))
15                 {
16                     return string.Empty;
17                 }
18                 var webClient = new System.Net.WebClient();
19                 NameValueCollection postValues = null;
20                 // 向服务器发送POST数据
21                 var url = string.Empty;
22                 if (Serve == 1)
23                 {
24                     url = "http://api.map.baidu.com/location/ip";
25                     postValues = new System.Collections.Specialized.NameValueCollection
26                             {
27                                 {"ak", "MRkBd6jnGOf8O5F58KKrvit5"},
28                                 {"ip", ipAddress},
29                                 {"coor", "bd09ll"}
30                             };
31                 }
32                 else if (Serve == 2)
33                 {
34                     url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php";
35                     postValues = new System.Collections.Specialized.NameValueCollection
36                             {
37                                 {"format", "json"},
38                                 {"ip", ipAddress}
39                             };
40                 }
41                 else
42                 {
43                     url = "http://ip.taobao.com/service/getIpInfo.php";
44                     postValues = new System.Collections.Specialized.NameValueCollection
45                             {
46                                 {"ip", ipAddress}
47                             };
48                 }
49
50                 byte[] responseArray = webClient.UploadValues(url, postValues);
51
52                 string response = System.Text.Encoding.UTF8.GetString(responseArray);
53
54                 var dataJson = JObject.Parse(response);  //动态解析  正常的解析无法生效
55                 string address = string.Empty;
56                 //百度接口
57                 if (Serve == 1)
58                 {
59                     if (dataJson["status"].ToString() == "0")
60                     {
61                         address = dataJson["content"]["address_detail"]["province"] + "," + dataJson["content"]["address_detail"]["city"];
62                     }
63                 }
64                 //新浪接口
65                 else if (Serve == 2)
66                 {
67                     if (dataJson["ret"].ToString() == "1")
68                     {
69                         address = dataJson["province"] + "," + dataJson["city"];
70                     }
71                 }
72                 //淘宝接口
73                 else
74                 {
75                     if (dataJson["code"].ToString() == "0")
76                     {
77                         if (!string.IsNullOrEmpty(dataJson["data"]["region"].ToString()))
78                             address = dataJson["data"]["region"] + "," + dataJson["data"]["city"];
79                     }
80                 }
81                 if (string.IsNullOrEmpty(address))
82                 {
83                     address = "局域网";
84                 }
85                 return address;
86             }
87             catch(Exception ex)
88             {
89                 Console.WriteLine(ex.Message);
90                 return string.Empty;
91             }
92         }
93         #endregion

调用方式:

ipAddressName = ipHelper.GetAddress(2, ipaddress);//调用新浪接口返回数据
时间: 2024-12-16 23:16:15

根据Ip获取城市帮助类的相关文章

DELPHI调用百度定位API(根据IP获取城市及GPS信息等)

缘由:因智能助理在用户说出“天气如何”时,需要自动获取城市,所以这里需要根据用户IP自动获取城市,所以有了这篇文章 QQ508882988 //根据百度API,根据来访IP自动获取出该IP所在的位置及更多信息,参数IP为空时,会使用当前访问者的IP地址作为定位参数 //sServerAK为用户密钥 string 必选,在lbs云官网注册的access key,作为访问的依据,定期从http://lbsyun.baidu.com/apiconsole/key获取 //参考http://lbsyun

php 获取IP 根据IP 获取城市信息 判断是否手机登陆

function GetIp(){ $realip = ''; $unknown = 'unknown'; if (isset($_SERVER)){ if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){ $arr = explode('

C# 解析百度天气数据,Rss解析百度新闻以及根据IP获取所在城市

百度天气 接口地址:http://api.map.baidu.com/telematics/v3/weather?location=上海&output=json&ak=hXWAgbsCC9UTkBO5V5Qg1WZ9,其中ak是密钥,自行去申请即可,便于大家测试,楼主就公布并了自己的Key,这样可以直接获取到数据. 获取到的数据是这样的: {"error":0,"status":"success","date"

IOS-根据ip获取当前城市的编号

IOS 通过ip地址获取当前城市的编号 //解析网址通过ip 获取城市天气代码    NSURL *url = [NSURL URLWithString:@"http://61.4.185.48:81/g/"];        //    定义一个NSError对象,用于捕获错误信息    NSError *error;    NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8Stri

百度地图API的IP定位城市和浏览器定位(转)

百度地图API提供了Geolocation 和 LocalCity两个服务类. 这俩API可以分别供用户在JavaScript中进行定位和城市确认. 1 本质上,Geolocation这个类是使用了支持HTML5浏览器提供的Geolocation API 来进行定位的.目前Internet Explorer 9.Firefox.Chrome.Safari 以及 Opera 支持地理定位(因为他们支持HTML5). 2 本质上,LocalCity这个类是利用用户IP地址去百度数据库里查询得到IP所

更具IP获得城市信息(百度API的运用)

    /**      * 根据IP获取城市      * @param string $ip ip地址      * @return array      * http://api.map.baidu.com/location/ip?ak=32f38c9491f2da9eb61106aaab1e9739&ip="+ip      */     public function getCityByIp($ip)     {         $result = false;        

php 通过ip获取所在城市地址信息 获取计算机外网ip

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-

PHP获取IP地址及根据IP判断城市实现城市切换或跳转

PHP获取IP地址 这个比较简单了,利用PHP自带函数就可以了,PHP中文手册看一下,都有现成的例子,就不过多说明了,直接上代码,A段: ? <? //PHP获取当前用户IP地址方法 $xp_UserIp = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"]; $xp_UserIp = ($xp_UserIp) ? $xp_

C# 根据IP地址获取城市

1 using System; 2 using System.IO; 3 using System.Net; 4 using System.Text; 5 using System.Web.Script.Serialization; 6 7 namespace IpUtils 8 { 9 public class IpDetail 10 { 11 public String Ret { get; set; } 12 13 public String Start { get; set; } 14