博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
获取用户登陆所在的ip及获取所属信息
阅读量:5162 次
发布时间:2019-06-13

本文共 9416 字,大约阅读时间需要 31 分钟。

package com.tcl.topsale.download.entity;public class GeoLocation {    private String countryCode;    private String countryName;    private String region;    private String regionName;    private String city;    private String postalCode;    private String latitude;    private String longitude;    public String getCountryCode() {        return countryCode;    }    public void setCountryCode(String countryCode) {        this.countryCode = countryCode;    }    public String getCountryName() {        return countryName;    }    public void setCountryName(String countryName) {        this.countryName = countryName;    }    public String getRegion() {        return region;    }    public void setRegion(String region) {        this.region = region;    }    public String getRegionName() {        return regionName;    }    public void setRegionName(String regionName) {        this.regionName = regionName;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    public String getPostalCode() {        return postalCode;    }    public void setPostalCode(String postalCode) {        this.postalCode = postalCode;    }    public String getLatitude() {        return latitude;    }    public void setLatitude(String latitude) {        this.latitude = latitude;    }    public String getLongitude() {        return longitude;    }    public void setLongitude(String longitude) {        this.longitude = longitude;    }        @Override    public String toString() {        return "GeoLocation [countryCode=" + countryCode + ", countryName="                + countryName + ", region=" + region + ", regionName="                + regionName + ", city=" + city + ", postalCode=" + postalCode                + ", latitude=" + latitude + ", longitude=" + longitude + "]";    }}
package com.tcl.topsale.download.util;import java.io.File;import java.io.IOException;import java.net.InetAddress;import java.net.URL;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.maxmind.geoip2.DatabaseReader;import com.maxmind.geoip2.exception.GeoIp2Exception;import com.maxmind.geoip2.model.CityResponse;import com.maxmind.geoip2.record.City;import com.maxmind.geoip2.record.Country;import com.maxmind.geoip2.record.Subdivision;import com.tcl.topsale.download.entity.GeoLocation;import com.weihua.common.base.action.BaseAction;/** *  * @author fzl *根据用户登陆ip获取国家code */public class GeoLocationUtil extends BaseAction{        /**     *      */    private static final long serialVersionUID = 1L;    private DatabaseReader reader;    private static Logger logger = LoggerFactory.getLogger(GeoLocationUtil.class);    public GeoLocationUtil() {        String dataFile = "com/tcl/topsale/download/util/GeoLite2-City.mmdb";        URL url = getClass().getClassLoader().getResource(dataFile);                if (url == null) {            System.err.println("location database is not found - " + dataFile);        } else {            try {                File database = new File(url.getPath());                System.out.println(new DatabaseReader.Builder(database).build()+"***************");                reader = new DatabaseReader.Builder(database).build();            } catch (Exception e) {                e.printStackTrace();            }        }    }//    public static void main(String[] args) {//        GeoLocationUtil glt = new GeoLocationUtil();//        String ip = "114.119.117.180";//        glt.getLocationFromRequest(ip);//        System.out.println(glt.getLocationFromRequest(ip));//    }        /**     * 获取ip地址映射的国家     * @param ipAddress     * @return     */    public GeoLocation getLocationFromRequest(String ip) {        GeoLocation location = getLocationV2(ip);        return location;    }        /**     * 获取ip地址     * @param request     * @return     */    public String getIpAddr(HttpServletRequest request) {        String ip = request.getHeader("x-forwarded-for");        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {            ip = request.getHeader("Proxy-Client-IP");        }        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {            ip = request.getHeader("WL-Proxy-Client-IP");        }        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {            ip = request.getRemoteAddr();        }        logger.info("Ip from user agent: {}", ip);        // 多个反向代理IP时,取第一个        int commaOffset = ip.indexOf(',');        if (commaOffset < 0) {            ip = ip.equals("0:0:0:0:0:0:0:1") ? "61.183.88.58" : ip;            return ip;        }        ip = ip.substring(0, commaOffset);                ip = ip.equals("0:0:0:0:0:0:0:1") ? "61.183.88.58" : ip;            return ip;    }        /**     * 获取ip地址映射的国家     * @param ipAddress     * @return     */    private GeoLocation getLocationV2(String ipAddress) {        GeoLocation geoLocation = null;        if (null == reader) {            //System.err.println("location database is not found.");            logger.error("location database is not found.");        } else {            try {                geoLocation = new GeoLocation();                InetAddress ipAdd = InetAddress.getByName(ipAddress);                CityResponse response = reader.city(ipAdd);                Country country = response.getCountry();                geoLocation.setCountryCode(country.getIsoCode());                geoLocation.setCountryName(country.getName());                Subdivision subdivision = response.getMostSpecificSubdivision();                geoLocation.setRegionName(subdivision.getName());                City city = response.getCity();                geoLocation.setCity(city.getName());                geoLocation.setPostalCode(response.getPostal().getCode());                geoLocation.setLatitude(String.valueOf(response.getLocation().getLatitude()));                geoLocation.setLongitude(String.valueOf(response.getLocation().getLongitude()));            } catch (IOException e) {                e.printStackTrace();                logger.error(e.getMessage());            } catch (GeoIp2Exception e) {                e.printStackTrace();                logger.error(e.getMessage());            }        }        return geoLocation;    }        //    public static void main(String[] args) throws Exception{//        File database = new File("D:/定位/GeoLite2-City.mmdb");//        DatabaseReader reader = new DatabaseReader.Builder(database).build();//        InetAddress ipAddress = InetAddress.getByName("14.106.124.11");//        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'//        System.out.println(city.getNames().get("zh-CN")); // '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//    }}

需要用到 :GeoLite2-City.mmdb,

geoip2-2.2.0.jar,jackson-databind-2.5.3.jar,google-http-client-1.20.0.jar,

maxmind-db-1.0.0.jar,jackson-annotations-2.5.0.jar,core-2.5.3.jar,jsr305-1.3.9.jar

 <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>

package com.tcl.topsale.download.entity;

public class GeoLocation {private String countryCode;private String countryName;private String region;private String regionName;private String city;private String postalCode;private String latitude;private String longitude;public String getCountryCode() {return countryCode;}public void setCountryCode(String countryCode) {this.countryCode = countryCode;}public String getCountryName() {return countryName;}public void setCountryName(String countryName) {this.countryName = countryName;}public String getRegion() {return region;}public void setRegion(String region) {this.region = region;}public String getRegionName() {return regionName;}public void setRegionName(String regionName) {this.regionName = regionName;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getPostalCode() {return postalCode;}public void setPostalCode(String postalCode) {this.postalCode = postalCode;}public String getLatitude() {return latitude;}public void setLatitude(String latitude) {this.latitude = latitude;}public String getLongitude() {return longitude;}public void setLongitude(String longitude) {this.longitude = longitude;}
@Overridepublic String toString() {return "GeoLocation [countryCode=" + countryCode + ", countryName="+ countryName + ", region=" + region + ", regionName="+ regionName + ", city=" + city + ", postalCode=" + postalCode+ ", latitude=" + latitude + ", longitude=" + longitude + "]";}}

 

转载于:https://www.cnblogs.com/Yusco/p/10766438.html

你可能感兴趣的文章
实验二:编写输出"Hello World!"
查看>>
cocos2d关于glew32.lib错误(转)
查看>>
菜单和工具条(二)
查看>>
面试经验[all]
查看>>
算法笔记
查看>>
6 行为型模式之 - 命令模式
查看>>
Mvc ModelState.isValid为false时,检查时那个字段不符合规则的代码
查看>>
Python 之 基础知识(三)
查看>>
cluster集群
查看>>
搞JAVA在北京月薪15K的朋友来到厦门却很难找到工作
查看>>
冒泡数组排序
查看>>
kibana5画图
查看>>
类的加载和反射
查看>>
Linux学习笔记四
查看>>
JavaScript
查看>>
[转]getHibernateTemplate出现的所有find方法的总结
查看>>
【转】HTTP中的长连接和短连接分析
查看>>
scala 基本语法
查看>>
2019.08.02 学习整理
查看>>
JavaScript面向对象基础语法总结
查看>>