您现在的位置: 爱51代码网 >> 范文 >> 文章正文
Java通过IP地址获取用户所在地源代码
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]  ... 下一页  >> 

  • 上一篇文章:

  • 下一篇文章: 没有了
  • 最新文章 热点文章 相关文章
    android手机无法与eclipse或电脑
    C/C++洗牌算法源代码
    servlet技术实现用户名唯一的验证
    E-business suite system servic
    ZOJ 3700 Ever Dream 文章中单词
    TortoiseGit和msysGit安装及使用
    asp中有一段javascipt的网页鼠标
    sharepoint 2010 获取用户信息Us
    设计包含max函数的队列
    随机从数组中取出指定的不重复的
    ZOJ 3700 Ever Dream 文章中单词
    TortoiseGit和msysGit安装及使用
    sharepoint 2010 获取用户信息Us
    mysql主从同步延迟方案解决的学习
    生日旅行总结
    中小板生日快乐随感
    送生日快乐桑葚乳酪小蛋糕
    写给女儿的生日快乐
    总分公司财务核算
    恢复使用繁体字可行性研究报告
    android编译时出现'Unab
    Android 仿 WP7 布局
    windows下搭建SVN服务器及配
    javascript中级联下拉列表
    jsp页面中表单action=“”为
    当session失效后重新登录成功
    jsp页面中点击导航字,右边输
    java线程同步的方法
    java数据连接池的工作机制是
    forward和redirect的区别
     



    设为首页 | 加入收藏 | 网站地图 | 友情链接 |