本文主要演示怎么根据IP地址定位国家,城市,经度纬度。

1.GeoLite数据库

MaxMind提供一个GeoLite的数据库(包含IP地址和位置信息)。

先下载一个GeoLite的免费数据库--下载

使用GeoIP的Java AIP获取位置信息--查看

开始编码。

2.GeoLite例子

我们演示如何使用GeoIP的客户端,查询IP地址的位置信息。

package com.qiyadeng.core;

import java.io.File;

import java.net.InetAddress;

import com.maxmind.geoip2.DatabaseReader;

import com.maxmind.geoip2.model.CityResponse;

import com.maxmind.geoip2.record.City;

import com.maxmind.geoip2.record.Country;

import com.maxmind.geoip2.record.Location;

import com.maxmind.geoip2.record.Postal;

import com.maxmind.geoip2.record.Subdivision;

public class GeoIpExample {

public static void main(String[] args) throws Exception{

// A File object pointing to your GeoIP2 or GeoLite2 database

File database = new File("c://temp//GeoLite2-City.mmdb");

// This creates the DatabaseReader object, which should be reused across

// lookups.

DatabaseReader reader = new DatabaseReader.Builder(database).build();

InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

// Replace "city" with the appropriate method for your database, e.g.,

// "country".

CityResponse response = reader.city(ipAddress);

Country country = response.getCountry();

System.out.println(country.getIsoCode()); // 'US'

System.out.println(country.getName()); // 'United States'

System.out.println(country.getNames().get("zh-CN")); // '美国'

Subdivision subdivision = response.getMostSpecificSubdivision();

System.out.println(subdivision.getName()); // 'Minnesota'

System.out.println(subdivision.getIsoCode()); // 'MN'

City city = response.getCity();

System.out.println(city.getName()); // 'Minneapolis'

Postal postal = response.getPostal();

System.out.println(postal.getCode()); // '55455'

Location location = response.getLocation();

System.out.println(location.getLatitude()); // 44.9733

System.out.println(location.getLongitude()); // -93.2323

}

}

输出结果如下:

US

United States

美国

Minnesota

MN

Minneapolis

55414

44.9759

-93.2166

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐