第一步:搭建环境https://blog.csdn.net/qq_32079585/article/details/85338884
第二步:写test代码(数据库放到D盘了,请保持路径的正确性)

package s.jf3q.com.test;

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 TestGeopip2 {
	public static void main(String[] args) throws Exception{      
	      // 创建 GeoLite2 数据库     
	      File database = new File("D://GeoLite2-City.mmdb");     
	      // 读取数据库内容   
	      DatabaseReader reader = new DatabaseReader.Builder(database).build();       
	      InetAddress ipAddress = InetAddress.getByName("54.38.228.35");     

	      // 获取查询结果      
	      CityResponse response = reader.city(ipAddress);     

	      // 获取国家信息
	      Country country = response.getCountry();
	      System.out.println(country.getIsoCode());               // 'CN'
	      System.out.println(country.getName());                  // 'China'
	      System.out.println(country.getNames().get("zh-CN"));    // '中国'

	      // 获取省份
	      Subdivision subdivision = response.getMostSpecificSubdivision();
	      System.out.println(subdivision.getName());   // 'Guangxi Zhuangzu Zizhiqu'
	      System.out.println(subdivision.getIsoCode()); // '45'
	      System.out.println(subdivision.getNames().get("zh-CN")); // '广西壮族自治区'

	      // 获取城市
	      City city = response.getCity();
	      System.out.println(city.getName()); // 'Nanning'
	      Postal postal = response.getPostal();
	      System.out.println(postal.getCode()); // 'null'
	      System.out.println(city.getNames().get("zh-CN")); // '北京'
	      Location location = response.getLocation();
	      System.out.println(location.getLatitude());  // 22.8167
	      System.out.println(location.getLongitude()); // 108.3167
	      
	     

	}  
	 
}

运行结果:根据客户端ip获取城市
又不懂的请联系我抠1913284695

相关文章: