|  
 
 
Java通过IP地址获取用户所在地源代码 
最近在做一个互联网项目,不可避免和其他互联网项目一样,需要各种类似的功能。其中一个就是通过用户访问网站的IP地址显示当前用户所在地。在没有查阅资料之前,我第一个想到的是应该有这样的RESTFUL服务,可能会有免费的,也有可能会是收费的。后来查阅了相关资料和咨询了客服人员发现了一款相当不错的库:GEOIP。 
中文官网:http-://www.maxmind.-com/zh/home?pkit_lang=zh 
英文官网:http-://www.maxmind.-com/en/home 
而且GeoIP也提供了如我之前猜测的功能:Web Services,具体可以看这里:http:-//dev.maxmind.-com/geoip/legacy/web-services 
这里我就把官方的实例搬过来吧,Web Services : 
首先来个Java 版本: 
 [java] view plaincopyprint? 01.import java.net.MalformedURLException;   02.import java.net.URL;   03.import java.io.BufferedReader;   04.import java.io.InputStreamReader;   05.import java.io.IOException;   06.   07.public class OmniReader {   08.    public static void main(String[] args) throws Exception {   09.        String license_key = "YOUR_LICENSE_KEY";   10.        String ip_address = "24.24.24.24";   11.   12.        String url_str = "http://geoip.maxmind.com/e?l=" + license_key + "&i=" + ip_address;   13.   14.        URL url = new URL(url_str);   15.        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));   16.        String inLine;   17.           18.        while ((inLine = in.readLine()) != null) {   19.            // Alternatively use a CSV parser here.    20.            Pattern p = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");    21.            Matcher m = p.matcher(inLine);   22.   23.            ArrayList fields = new ArrayList();   24.            String f;   25.            while (m.find()) {   26.                f = m.group(1);   27.                if (f!=null) {   28.                    fields.add(f);   29.                }   30.              
 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]  ... 下一页  >>  
 |