引用網址:http://www.qiyadeng.com/post/java-ip

本文主要演示怎麼根據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
 

arrow
arrow
    文章標籤
    java GeoLite GeoIP IP定位
    全站熱搜

    龍之家族 發表在 痞客邦 留言(0) 人氣()