根据IP查询用户地理位置
一、从request请求中获取用户ip地址
package com.ssy.utils;
import javax.servlet.http.HttpServletRequest;
public class IPUtil {
public static String getIPAddress(HttpServletRequest request) {
String ip = null;
//X-Forwarded-For:Squid 服务代理
String ipAddresses = request.getHeader("X-Forwarded-For");
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//Proxy-Client-IP:apache 服务代理
ipAddresses = request.getHeader("Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//WL-Proxy-Client-IP:weblogic 服务代理
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//HTTP_CLIENT_IP:有些代理服务器
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
//X-Real-IP:nginx服务代理
ipAddresses = request.getHeader("X-Real-IP");
}
//有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
if (ipAddresses != null && ipAddresses.length() != 0) {
ip = ipAddresses.split(",")[0];
}
//还是不能获取到,最后再通过request.getRemoteAddr();获取
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
二、调用淘宝api解析IP地址
package com.ssy.utils;
import java.io.UnsupportedEncodingException;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class AddressUtil {
public static String getAddresses(String content, String encodingString)
throws UnsupportedEncodingException {
// 这里调用淘宝API
String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
// 从http://whois.pconline.com.cn取得IP所在的省市区信息
String returnStr = getResult(urlStr, content, encodingString);
if (returnStr != null) {
// 处理返回的省市区信息
returnStr = decodeUnicode(returnStr);
String[] temp = returnStr.split(",");
if (temp.length < 3) {
return "0";//无效IP,局域网测试
}
return returnStr;
}
return null;
}
private static String getResult(String urlStr, String content, String encoding) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();// 新建连接实例
connection.setConnectTimeout(8000);// 设置连接超时时间,单位毫秒
connection.setReadTimeout(8000);// 设置读取数据超时时间,单位毫秒
connection.setDoOutput(true);// 是否打开输出流 true|false
connection.setDoInput(true);// 是否打开输入流true|false
connection.setRequestMethod("POST");// 提交方法POST|GET
connection.setUseCaches(false);// 是否缓存true|false
connection.connect();// 打开连接端口
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());// 打开输出流往对端服务器写数据
out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
out.flush();// 刷新
out.close();// 关闭输出流
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
// ,以BufferedReader流来读取
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();// 关闭连接
}
}
return null;
}
/**
* unicode 转换成 中文
*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuilder outBuffer = new StringBuilder(len);
for (int x = 0; x < len; ) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
aChar = '\t';
} else if (aChar == 'r') {
aChar = '\r';
} else if (aChar == 'n') {
aChar = '\n';
} else if (aChar == 'f') {
aChar = '\f';
}
outBuffer.append(aChar);
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
}
三、使用geoLite2-city数据库文件解析IP地址
将GeoLite2-City.mmdb导入resources下,获取InputStream。
链接:https://pan.baidu.com/s/1CFNm7Z6agWKAHlNZOSD0OA
提取码:r6dd
package com.ssy.utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Subdivision;
public class AddressUtil {
private static DatabaseReader reader;
private static ReentrantLock lock = new ReentrantLock();
static {
load();
}
public static String findOne(String ip) {
String[] ipAddrs = find(ip);
if (ipAddrs != null && ipAddrs.length > 0) {
StringBuilder addrBuilder = new StringBuilder();
for (String addr : ipAddrs) {
addrBuilder.append(addr);
}
return addrBuilder.toString();
}
return null;
}
public static String[] find(String ip) {
try {
String addr[] = new String[3];
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
CityResponse response = reader.city(ipAddress);
// 获取国家名称
Country country = response.getCountry();
addr[0] = country.getNames().get("zh-CN");
// 获取省分名称
Subdivision subdivision = response.getMostSpecificSubdivision();
addr[1] = subdivision.getNames().get("zh-CN") == null? "":subdivision.getNames().get("zh-CN");
// 获取城市名称
City city = response.getCity();
addr[2] = city.getNames().get("zh-CN")== null? "":city.getNames().get("zh-CN");
return addr;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void load() {
lock.lock();
// 创建 GeoLite2 数据库
InputStream database = AddressUtil.class.getResourceAsStream("/GeoLite2-City.mmdb");
// 读取数据库内容
try {
reader = new DatabaseReader.Builder(database).build();
} catch (IOException e) {
e.printStackTrace();
} finally {
lock.unlock();
try {
if (null != database) {
database.close();
}
} catch (IOException e) {
}
}
}
}