C#通过HTTP请求查询获取IP地址对应的地理位置信息
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/423
样例:
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-19 16:02:08