通过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="4" 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>
View Code
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 > 0)
                {
                    foreach (var ip in ips)
                    {
                        var rs = 0;
                        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();
View Code
/// <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[1].Value, 16)).ToString(); });
        }
View Code
/// <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 = 0; i < data.Count; i++)
                {
                    buffer = encoding.GetBytes(data.Keys[i]);
                    if (i > 0)
                        ms.WriteByte(Convert.ToByte('&'));
                    ms.Write(buffer, 0, buffer.Length);
                    ms.WriteByte(Convert.ToByte('='));
                    buffer = encoding.GetBytes(HttpUtility.UrlEncode(data[i]));
                    ms.Write(buffer, 0, buffer.Length);
                }
                buffer = ms.ToArray();
            }

            request.ContentLength = buffer.Length;
            using (System.IO.Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(buffer, 0, 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();
            }
        }
View Code

运行效果:

2、  直接请求网页:

这种方式很不建议使用,从网页生扒html信息,很不稳定,一旦别人的网页模板或者样式一旦改变,自己的代码也要跟着改变,很头痛的,一般都不建议采用这种方式,能够找到接口的最好用别人提供的api,下面提供一个地址让有兴趣的人去研究一下:

http://www.jb51.net/article/33540.htm

posted @ 2014-04-11 13:10  yycx0328  阅读(7349)  评论(6编辑  收藏  举报