• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

maxmind/GeoIP2-java: Java API for GeoIP2 webservice client and database reader

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

maxmind/GeoIP2-java

开源软件地址:

https://github.com/maxmind/GeoIP2-java

开源编程语言:

Java 98.7%

开源软件介绍:

GeoIP2 Java API

Description

This distribution provides an API for the GeoIP2 and GeoLite2 web services and databases.

Installation

Maven

We recommend installing this package with Maven. To do this, add the dependency to your pom.xml:

    <dependency>
        <groupId>com.maxmind.geoip2</groupId>
        <artifactId>geoip2</artifactId>
        <version>3.0.1</version>
    </dependency>

Gradle

Add the following to your build.gradle file:

repositories {
    mavenCentral()
}
dependencies {
    compile 'com.maxmind.geoip2:geoip2:3.0.1'
}

JAR Files

If you are unable to use Maven or Gradle, you may include the geoip2.jar file and its dependencies in your classpath. Download the JAR files from the GitHub Releases page.

IP Geolocation Usage

IP geolocation is inherently imprecise. Locations are often near the center of the population. Any location provided by a GeoIP2 database or web service should not be used to identify a particular address or household.

Web Service Usage

To use the web service API, you must create a new WebServiceClient using the WebServiceClient.Builder. You must provide the Builder constructor your MaxMind accountId and licenseKey. To use the GeoLite2 web services instead of GeoIP2, set the host method on the builder to geolite.info. You may also set a timeout or set the locales fallback order using the methods on the Builder. After you have created the WebServiceClient, you may then call the method corresponding to a specific end point, passing it the IP address you want to look up.

If the request succeeds, the method call will return a model class for the end point you called. This model in turn contains multiple record classes, each of which represents part of the data returned by the web service.

If the request fails, the client class throws an exception.

The WebServiceClient object is safe to share across threads. If you are making multiple requests, the object should be reused so that new connections are not created for each request.

See the API documentation for more details.

Web Service Example

Country Service

// This creates a WebServiceClient object that is thread-safe and can be
// reused across requests. Reusing the object will allow it to keep
// connections alive for future requests.
//
// Replace "42" with your account ID and "license_key" with your license key.
// To use the GeoLite2 web service instead of the GeoIP2 web service, call the
// host method on the builder with "geolite.info", e.g.
// new WebServiceClient.Builder(42, "license_key").host("geolite.info").build()
WebServiceClient client = new WebServiceClient.Builder(42, "license_key")
    .build();

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

// Do the lookup
CountryResponse response = client.country(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")); // '美国'

City Plus Service

// This creates a WebServiceClient object that is thread-safe and can be
// reused across requests. Reusing the object will allow it to keep
// connections alive for future requests.
//
// Replace "42" with your account ID and "license_key" with your license key.
// To use the GeoLite2 web service instead of the GeoIP2 web service, call the
// host method on the builder with "geolite.info", e.g.
// new WebServiceClient.Builder(42, "license_key").host("geolite.info").build()
WebServiceClient client = new WebServiceClient.Builder(42, "license_key")
    .build();

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

// Do the lookup
CityResponse response = client.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

Insights Service

// This creates a WebServiceClient object that is thread-safe and can be
// reused across requests. Reusing the object will allow it to keep
// connections alive for future requests.
//
// Replace "42" with your account ID and "license_key" with your license key.
// Please note that the GeoLite2 web service does not support Insights.
WebServiceClient client = new WebServiceClient.Builder(42, "license_key")
    .build();

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

// Do the lookup
InsightsResponse response = client.insights(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")); // '美国'
System.out.println(country.getConfidence());         // 99

Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName());       // 'Minnesota'
System.out.println(subdivision.getIsoCode());    // 'MN'
System.out.println(subdivision.getConfidence()); // 90

City city = response.getCity();
System.out.println(city.getName());       // 'Minneapolis'
System.out.println(city.getConfidence()); // 50

Postal postal = response.getPostal();
System.out.println(postal.getCode());       // '55455'
System.out.println(postal.getConfidence()); // 40

Location location = response.getLocation();
System.out.println(location.getLatitude());        // 44.9733
System.out.println(location.getLongitude());       // -93.2323
System.out.println(location.getAccuracyRadius());  // 3
System.out.println(location.getTimeZone());        // 'America/Chicago'

System.out.println(response.getTraits().getUserType()); // 'college'

Database Usage

To use the database API, you must create a new DatabaseReader using the DatabaseReader.Builder. You must provide the Builder constructor either an InputStream or File for your GeoIP2 database. You may also specify the fileMode and the locales fallback order using the methods on the Builder object.

After you have created the DatabaseReader, you may then call one of the appropriate methods, e.g., city or tryCity, for your database. These methods take the IP address to be looked up. The methods with the try prefix return an Optional object, which will be empty if the value is not present in the database. The method without the prefix will throw an AddressNotFoundException if the address is not in the database. If you are looking up many IPs that are not contained in the database, the try method will be slightly faster as they do not need to construct and throw an exception. These methods otherwise behave the same.

If the lookup succeeds, the method call will return a response class for the GeoIP2 lookup. The class in turn contains multiple record classes, each of which represents part of the data returned by the database.

We recommend reusing the DatabaseReader object rather than creating a new one for each lookup. The creation of this object is relatively expensive as it must read in metadata for the file. It is safe to share the object across threads.

See the API documentation for more details.

Caching

The database API supports pluggable caching (by default, no caching is performed). A simple implementation is provided by com.maxmind.db.CHMCache. Using this cache, lookup performance is significantly improved at the cost of a small (~2MB) memory overhead.

Usage:

new DatabaseReader.Builder(file).withCache(new CHMCache()).build();

Packaging Database in a JAR

If you are packaging the database file as a resource in a JAR file using Maven, you must disable binary file filtering. Failure to do so will result in InvalidDatabaseException exceptions being thrown when querying the database.

Database Example

City

// A File object pointing to your GeoIP2 or GeoLite2 database
File database = new File("/path/to/GeoIP2-City.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
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

Anonymous IP

// A File object pointing to your GeoIP2 Anonymous IP database
File database = new File("/path/to/GeoIP2-Anonymous-IP.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
try (DatabaseReader reader = new DatabaseReader.Builder(database).build()) {
    InetAddress ipAddress = InetAddress.getByName("85.25.43.84");

    AnonymousIpResponse response = reader.anonymousIp(ipAddress);

    System.out.println(response.isAnonymous()); // true
    System.out.println(response.isAnonymousVpn()); // false
    System.out.println(response.isHostingProvider()); // false
    System.out.println(response.isPublicProxy()); // false
    System.out.println(response.isResidentialProxy()); // false
    System.out.println(response.isTorExitNode()); //true
}

ASN

// A File object pointing to your GeoLite2 ASN database
File database = new File("/path/to/GeoLite2-ASN.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
try (DatabaseReader reader = new DatabaseReader.Builder(database).build()) {

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

    AsnResponse response = reader.asn(ipAddress);

    System.out.println(response.getAutonomousSystemNumber());       // 217
    System.out.println(response.getAutonomousSystemOrganization()); // 'University of Minnesota'
}

Connection-Type

// A File object pointing to your GeoIP2 Connection-Type database
File database = new File("/path/to/GeoIP2-Connection-Type.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();

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

ConnectionTypeResponse response = reader.connectionType(ipAddress);

// getConnectionType() returns a ConnectionType enum
ConnectionType type = response.getConnectionType();

System.out.println(type); // 'Corporate'

Domain

// A File object pointing to your GeoIP2 Domain database
File database = new File("/path/to/GeoIP2-Domain.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();

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

DomainResponse response = reader.domain(ipAddress);

System.out.println(response.getDomain()); // 'Corporate'

Enterprise

// A File object pointing to your GeoIP2 Enterprise database
File database = new File("/path/to/GeoIP2-Enterprise.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
try (DatabaseReader reader = new DatabaseReader.Builder(database).build()) {
    InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

    //  Use the enterprise(ip) method to do a lookup in the Enterprise database
    EnterpriseResponse response = reader.enterprise(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")); // '美国'
    System.out.println(country.getConfidence());         // 99

    Subdivision subdivision = response.getMostSpecificSubdivision();
    System.out.println(subdivision.getName());           // 'Minnesota'
    System.out.println(subdivision.getIsoCode());        // 'MN'
    System.out.println(subdivision.getConfidence());     // 77

    City city = response.getCity();
    System.out.println(city.getName());       // 'Minneapolis'
    System.out.println(city.getConfidence()); // 11

    Postal postal = response.getPostal();
    System.out.println(postal.getCode()); // '55455'
    System.out.println(postal.getConfidence()); // 5

    Location location = response.getLocation();
    System.out.println(location.getLatitude());  // 44.9733
    System.out.println(location.getLongitude()); // -93.2323
    System.out.println(location.getAccuracyRadius()); // 50
}

ISP

// A File object pointing to your GeoIP2 ISP database
File database = new File("/path/to/GeoIP2-ISP.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();

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

IspResponse response = reader.isp(ipAddress);

System.out.println(response.getAutonomousSystemNumber());       // 217
System.out.println(response.getAutonomousSystemOrganization()); // 'University of Minnesota'
System.out.println(response.getIsp());                          // 'University of Minnesota'
System.out.println(response.getOrganization());                 // 'University of Minnesota'

Exceptions

For details on the possible errors returned by the web service itself, see the GeoIP2 web service documentation.

If the web service returns an explicit erro


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap