EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

C#通过HTTP请求查询获取IP地址对应的地理位置信息

样例:

static void Main(string[] args)
{
    //http://pv.sohu.com/cityjson?ie=utf-8
    //http://ip-api.com/json/115.191.200.34?lang=zh-CN

    string Content ="";
    string ip = "114.114.114.114";
    string url = "http://ip-api.com/json/"+ip+"?lang=zh-CN";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader readStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
    {
        while (!readStream.EndOfStream)
        {
            Content += readStream.ReadLine();
        }
    }
    IPTokenModel apiResult = JsonConvert.DeserializeObject<IPTokenModel>(Content);
    Console.WriteLine(apiResult.query);
    Console.WriteLine(apiResult.country);
    Console.WriteLine(apiResult.regionName);
    Console.WriteLine(apiResult.city);
    Console.WriteLine(apiResult.status);
    Console.ReadLine();
}

IPTokenModel.cs:

public class IPTokenModel
{
    public string status { get; set; }
    public string country { get; set; }
    public string regionName { get; set; }
    public string city { get; set; }
    public string query { get; set; }
}

 

This article was last edited at 2020-08-20 01:02:08

* *