最近公司写一个访问用户所在地区的统计,想来想去只能通过IP来确定用户的地区。于是自己整理的一套方法,仅供参考。
1、首先要把需要的jar包引入到maven库,如下:
<dependency>
<groupId>com.maxmind.geoip</groupId>
<artifactId>geoip-api</artifactId>
<version>1.2.10</version>
</dependency>
2、下载个IP寻址数据库,GeoLiteCity.dat。下载地址:
https://download.csdn.net/download/yanzi920403/12104724
3、准备工作完成,开始写代码。
//根据IP得出经纬度,怎么获取IP就不在累赘了
public static Location getXYByIp(String ip){
if (ip == null || "".equals(ip)||"127.0.0.1".equals(ip)) {
return null;
}
LookupService cl;
Location coordinate = null;
try {
cl = new LookupService("D://GeoLiteCity.dat", LookupService.GEOIP_MEMORY_CACHE);//文件地址尽量放在项目路径下,我这里用来测试就写了绝对路径
coordinate = cl.getLocation(ip);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return coordinate;
}
//根据经纬度得出 省、市、区、街道
public static String getAdd(String log, String lat ){
//lat 小 log 大
//参数解释: 纬度,经度 type 001 (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
String urlString = "http://gc.ditu.aliyun.com/regeocoding?l="+lat+","+log+"&type=010";
String res = "";
try {
URL url = new URL(urlString);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res += line+"\n";
}
in.close();
} catch (Exception e) {
System.out.println("error in wapaction,and e is " + e.getMessage());
}
System.out.println(res);
return res;
}
public static JSONObject getIPXY(String ip) {
JSONObject rtjson=new JSONObject();
if (idisNull(ip)) {
rtjson.put("status", "0");
rtjson.put("msg", "ip不能为空");
return rtjson;
}
//根据IP获取坐标
Location coordinate = getXYByIp(ip);
if (coordinate == null) {
rtjson.put("status", "0");
rtjson.put("msg", "ip不能为空");
return rtjson;
}
String add = getAdd(String.valueOf(coordinate.longitude), String.valueOf(coordinate.latitude));
JSONObject jsonObject = JSONObject.fromObject(add);
JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("addrList"));
JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));
String allAdd = j_2.getString("admName");
String arr[] = allAdd.split(",");
rtjson.put("city", arr[0]);//省
rtjson.put("country", coordinate.countryName);
rtjson.put("lng", coordinate.longitude);
rtjson.put("lat", coordinate.latitude);
rtjson.put("status", "1");
return rtjson;
}