Java代码如何使用IP地址查找位置呢?
下文笔者讲述使用IP地址查找位置的方法及示例分享,如下所示
IP地址查找位置
实现思路: 1.获取免费的GeoLite数据库(IP地址到位置) 2.获取GeoIP客户端Java API例:GeoLite获取GeoIP地址
package com.java265.analysis.location; import java.io.File; import java.io.IOException; import com.maxmind.geoip.Location; import com.maxmind.geoip.LookupService; import com.maxmind.geoip.regionName; import com.java265.analysis.location.mode.ServerLocation; public class GetLocationExample { public static void main(String[] args) { GetLocationExample obj = new GetLocationExample(); ServerLocation location = obj.getLocation("8.8.8.8"); System.out.println(location); } public ServerLocation getLocation(String ipAddress) { File file = new File( "C:\\resources\\location\\GeoLiteCity.dat"); return getLocation(ipAddress, file); } public ServerLocation getLocation(String ipAddress, File file) { ServerLocation serverLocation = null; try { serverLocation = new ServerLocation(); LookupService lookup = new LookupService(file,LookupService.GEOIP_MEMORY_CACHE); Location locationServices = lookup.getLocation(ipAddress); serverLocation.setCountryCode(locationServices.countryCode); serverLocation.setCountryName(locationServices.countryName); serverLocation.setRegion(locationServices.region); serverLocation.setRegionName(regionName.regionNameByCode( locationServices.countryCode, locationServices.region)); serverLocation.setCity(locationServices.city); serverLocation.setPostalCode(locationServices.postalCode); serverLocation.setLatitude(String.valueOf(locationServices.latitude)); serverLocation.setLongitude(String.valueOf(locationServices.longitude)); } catch (IOException e) { System.err.println(e.getMessage()); } return serverLocation; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。