license_key ); $uri->query_param( i => $ip_address );
my $ua = LWP::UserAgent->new( timeout => 5 ); my $response = $ua->get($uri);
die 'Request failed with status ' . $response->code() unless $response->is_success();
my $csv = Text::CSV_XS->new( { binary => 1 } ); $csv->parse( decode( 'ISO-8859-1', $response->content() ) );
my %omni; @omni{@fields} = $csv->fields();
binmode STDOUT, ':encoding(UTF-8)';
if ( defined $omni{error} && length $omni{error} ) { die "MaxMind returned an error code for the request: $omni{error}\n"; } else { print "\nMaxMind Omni data for $ip_address\n\n"; for my $field (@fields) { print sprintf( " %-20s %s\n", $field, $omni{$field} ); } print "\n"; } 以上都是基于Web Services的,这里我再写个使用本地库的实例,而项目中也使用的是本地库。
首先在项目中需要添加库文件:GeoLiteCity,然后就可以利用这个文件得到城市和国家信息了。项目中如何获取到用户访问的IP地址就不用我说了吧,做过Web开发的人应该都知道。Request里面获取。Java代码:
[java] view plaincopyprint? 01.public class GeoBusiness { 02. /** 03. * @param args 04. * @throws IOException 05. */ 06. public static void main(String[] args) throws IOException { 07. // TODO Auto-generated method stub 08. System.out.println(getLocationByIp("220.181.111.147").getCity()); 09. System.out.println(getLocationByIp("220.181.111.147").getCountryName()); 10. } 11. 12. public static Location getLocationByIp(String ipaddr) throws IOException { 13. String sep = System.getProperty("file.separator"); 14. String dir = Play.configuration.getProperty("geoip.datdir"); 15. String dbfile = dir + sep + "GeoLiteCity.dat"; 16. LookupService cl = new LookupService(dbfile, 17. LookupService.GEOIP_MEMORY_CACHE); 18. Location location = cl.getLocation(ipaddr); 19. 20. cl.close(); 21. return location; 22. } 23.} public class GeoBusiness { /** * @param args * @throws IOException */ public
上一页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] ... 下一页 >>
|