c#百度IP定位API使用方法

c#百度IP定位API使用方法

1.先建立一個收集信息的實體類

IPModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    public class IpModel
    {
        [Serializable]
        public class AddressForQueryIPFromBaidu { public string Address { get; set; } public Content Content { get; set; } public string Status { get; set; } }
        [Serializable]
        public class Content { public string Address { get; set; } public Address_Detail Address_Detail { get; set; } public Point Point { get; set; } }
        [Serializable]
        public class Address_Detail { public string City { get; set; } public string City_Code { get; set; } public string District { get; set; } public string Province { get; set; } public string Street { get; set; } public string Street_Number { get; set; } }
        [Serializable]
        public class Point { public string X { get; set; } public string Y { get; set; } }
    }
}

2.獲取客戶端IP:

string ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;

3.將獲得的IP放入以下函數中

   Model.IpModel.AddressForQueryIPFromBaidu baidu = GetAddressFromIP(ipAddress);
   baidu.Content.Address_Detail ;//獲取地址
GetAddressFromIP函數:
public static Model.IpModel.AddressForQueryIPFromBaidu GetAddressFromIP(string ip)
        {
            string baiduKey = "MXAEmre2rCTIYKSAMv1EVh0K"; 
            string url = "http://api.map.baidu.com/location/ip?ak=" + baiduKey +"&ip="+ip+ "&coor=bd09ll";   
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
            System.IO.Stream responseStream = response.GetResponseStream(); 
            System.IO.StreamReader sr = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8")); 
            string responseText = sr.ReadToEnd(); sr.Close(); sr.Dispose(); 
            responseStream.Close(); string jsonData = responseText; 
            JavaScriptSerializer jss = new JavaScriptSerializer(); 
            Model.IpModel.AddressForQueryIPFromBaidu addressForQueryIPFromBaidu = jss.Deserialize<Model.IpModel.AddressForQueryIPFromBaidu>(jsonData); 
            return addressForQueryIPFromBaidu; 
        }

此函數裏使用到了json需引用看上章

發佈了25 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章