通过ip地址获取当前地理位置
1、 使用接口的方式:
这种方式是相对稳定,而且提供的数据相对稳定,提供接口的地方很多,大家可以参照
http://www.hujuntao.com/api/the-ip-address-api-and-call-the-interface-method.html
不一一讲解,只讲解一下新浪提供的接口:
新浪接口地址:http://int.dpool.sina.com.cn/iplookup/iplookup.php
参数有两个:format和ip
1) IP:不传入ip值时默认为本机ip,也可以指定特定的ip地址;
2) format:返回给客户端的数据格式有js和json格式:
a、 返回js格式:
eg:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=115.29.28.108
返回结果:var remote_ip_info = {"ret":1,"start":"115.28.0.0","end":"115.29.255.255","country":"\u4e2d\u56fd","province":"\u5317\u4eac","city":"\u5317\u4eac","district":"","isp":"\u7535\u4fe1","type":"\u673a\u623f","desc":"\u4e2d\u56fd\u4e07\u7f51\u673a\u623f\u7535\u4fe1"};
返回的结果给一个js变量,变量值为json格式,可以自己将Unicode字符转码为中文:
var remote_ip_info = {"ret":1,"start":"115.28.0.0","end":"115.29.255.255","country":"中国","province":"北京","city":"北京","district":"","isp":"电信","type":"机房","desc":"中国万网机房电信"};
b、 返回json格式:
eg:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=115.29.28.108
返回结果:
{"ret":1,"start":"115.28.0.0","end":"115.29.255.255","country":"\u4e2d\u56fd","province":"\u5317\u4eac","city":"\u5317\u4eac","district":"","isp":"\u7535\u4fe1","type":"\u673a\u623f","desc":"\u4e2d\u56fd\u4e07\u7f51\u673a\u623f\u7535\u4fe1"}
返回的结果直接是一个json格式的字符串,可以自己将Unicode字符转码为中文:
{"ret":1,"start":"115.28.0.0","end":"115.29.255.255","country":"中国","province":"北京","city":"北京","district":"","isp":"电信","type":"机房","desc":"中国万网机房电信"}
代码示例:
<div>
<asp:GridView ID="gvDetail" runat="server" CellPadding="" ForeColor="#333333" GridLines="None"
Width="100%" AutoGenerateColumns="false">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
<Columns>
<asp:TemplateField HeaderText="IP地址">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("IP")%></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="国家">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("Country")%></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="省会">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("Province")%></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="城市">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("City")%></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="地区">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("District")%></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="运营商">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("Isp")%></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="类型">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("Type")%></div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="描述">
<ItemTemplate>
<div style=" text-align:center"><%#Eval("Desc")%></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
var ips = new List<string>();
ips.Add("101.36.93.107");
ips.Add("106.117.102.99");
ips.Add("111.206.170.45");
ips.Add("114.86.246.202");
ips.Add("116.55.250.58");
ips.Add("182.108.206.70");
ips.Add("36.250.249.232");
var list = new List<IPDetail>();
if (ips != null && ips.Count > )
{
foreach (var ip in ips)
{
var rs = ;
NameValueCollection vc = new NameValueCollection();
vc.Add("format", "json");
vc.Add("ip", ip);
string result = WebUtils.PostDataToUrl(postUrl, Encoding.UTF8, vc);
result = ConvertUnicode2Chinese(result);
if (!Int32.TryParse(result, out rs))
{
JObject obj = (JObject)JsonConvert.DeserializeObject(result);
if (obj != null)
{
var ipd = new IPDetail();
ipd.IP = ip;
ipd.Country = obj["country"].ToString();
ipd.Province = obj["province"].ToString();
ipd.City = obj["city"].ToString();
ipd.District = obj["district"].ToString();
ipd.Isp = obj["isp"].ToString();
ipd.Type = obj["type"].ToString();
ipd.Desc = obj["desc"].ToString();
list.Add(ipd);
}
}
}
} gvDetail.DataSource = list;
gvDetail.DataBind();
/// <summary>
/// 将Unicode编码转换成中文
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
private string ConvertUnicode2Chinese(string result)
{
Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
return reg.Replace(result, delegate(Match m)
{ return ((char)Convert.ToInt32(m.Groups[].Value, )).ToString(); });
}
/// <summary>
/// POST数据到指定地址
/// </summary>
/// <param name="url"></param>
/// <param name="encoding"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string PostDataToUrl(string url, System.Text.Encoding encoding, System.Collections.Specialized.NameValueCollection data)
{
//设置HttpWebRequest
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url));
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false; byte[] buffer;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
for (int i = ; i < data.Count; i++)
{
buffer = encoding.GetBytes(data.Keys[i]);
if (i > )
ms.WriteByte(Convert.ToByte('&'));
ms.Write(buffer, , buffer.Length);
ms.WriteByte(Convert.ToByte('='));
buffer = encoding.GetBytes(HttpUtility.UrlEncode(data[i]));
ms.Write(buffer, , buffer.Length);
}
buffer = ms.ToArray();
} request.ContentLength = buffer.Length;
using (System.IO.Stream requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, , buffer.Length);
requestStream.Close();
} try
{
//获取数据
using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)(request.GetResponse()))
using (System.IO.Stream stream = response.GetResponseStream())
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, encoding))
{
string result = reader.ReadToEnd();
reader.Close();
stream.Close();
response.Close();
return result;
}
}
finally
{
request.Abort();
}
}
运行效果:
2、 直接请求网页:
这种方式很不建议使用,从网页生扒html信息,很不稳定,一旦别人的网页模板或者样式一旦改变,自己的代码也要跟着改变,很头痛的,一般都不建议采用这种方式,能够找到接口的最好用别人提供的api,下面提供一个地址让有兴趣的人去研究一下:
http://www.jb51.net/article/33540.htm
通过ip地址获取当前地理位置的更多相关文章
- 腾讯新浪通过IP地址获取当前地理位置(省份)的接口
腾讯新浪通过IP地址获取当前地理位置(省份)的接口 腾讯的接口是 ,返回数组 http://fw.qq.com/ipaddress 返回值 var IPData = new Array(" ...
- 根据现有IP地址获取其地理位置(省份,城市等)的方法
根据现有IP地址获取其地理位置(省份,城市等)的方法 function GetIpLookup($ip = ''){ if(empty($ip)){ return '请输入IP地址'; } $res ...
- IP地址获取当前地理位置(省份)的接口
腾讯的接口是 ,返回数组 http://fw.qq.com/ipaddress 返回值 var IPData = new Array("61.135.152.194"," ...
- 转载:腾讯与新浪的通过IP地址获取当前地理位置(省份)的接口
腾讯的接口是 ,返回数组 http://fw.qq.com/ipaddress 返回值 var IPData = new Array("61.135.152.194"," ...
- js根据ip地址获取城市地理位置
一.使用js根据ip获取地址位置 <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>& ...
- php获取ip地址所在的地理位置的实现
1,通过腾讯或者新浪提供的接口来获取(新浪和腾讯类似) <?php function getIPLocation($queryIP){ $url = 'http://ip.qq ...
- 运用百度开放平台接口根据ip地址获取位置
使用百度开放平台接口根据ip地址获取位置 今天无意间发现在百度开放平台接口,就把一段代码拿了下来,有需要的可以试试看:http://opendata.baidu.com/api.php?query=5 ...
- Java根据ip地址获取Mac地址,Java获取Mac地址
Java根据ip地址获取Mac地址,Java获取Mac地址 >>>>>>>>>>>>>>>>>&g ...
- PHP:根据IP地址获取所在城市
文件目录: ipLocation -----qqwry ----------QQWry.Dat -----ipCity.class.php ipCity.class.php文件代码: <?php ...
随机推荐
- Unity3d 随机地图生成
2D解析图: 3D地形: 嘿嘿.
- 工作总结:检查字符串合法性(C++)
BOOL CLiftCtrlModbusConfigDlg::CheckValid(const CString &str) { ASSERT(str.GetLength() > ); ] ...
- 登录远程SQL服务器
一 看ping 服务器IP能否ping通. 这个实际上是看和远程sql server 2000服务器的物理连接是否存在.如果不行,请检查网络,查看配置,当然得确保远程sql server 2000服务 ...
- Borg Maze poj 3026
Description The Borg is an immensely powerful race of enhanced humanoids from the delta quadrant of ...
- DB2中时间格式化
values to_char(current timestamp - 7 hours,'hh24')||'点' values varchar(hour(current time + 5 hour))| ...
- 模态运行EXE程序
function ExecShowModal(APath: PChar; ACmdShow: Integer; ATimeout: Longword): Integer; var vStartupIn ...
- RR区间锁 不是唯一索引,即使区间内没值,也锁
+--------- +---------------------------------------------------------------------------------------- ...
- 解决Failed to connect session for conifg 故障
服务器升级openssh之后jenkins构建报错了,报错信息如下: Failed to connet or change directory jenkins.plugins.publish_over ...
- 网络编程-pcap数据包格式
Libpcap的官方网站是http://www.tcpdump.org/,该项目和Tcpdump项目是同一个团队维护.Libpcap是一个平台独立的 数据包捕获开发包,制定了数据包离线存储的事实标准. ...
- [Locked] Longest Substring with At Most Two Distinct Characters
Longest Substring with At Most Two Distinct Characters Given a string, find the length of the longes ...