代码语言:javascript复制
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author : zanglikun
* @date : 2020/8/6 11:03
* @Version: 1.0
* @Desc : 获取IP 与 地理位置
*/
public class IpGeoUtils {
/**
* 传入Request 获取真实IP
*
* @param request
* @return
*/
public static String getRealIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
//System.out.println("x-forwarded-for ip: " ip);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
if (ip.indexOf(",") != -1) {
ip = ip.split(",")[0];
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
//System.out.println("Proxy-Client-IP ip: " ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
//System.out.println("WL-Proxy-Client-IP ip: " ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
//System.out.println("HTTP_CLIENT_IP ip: " ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//System.out.println("HTTP_X_FORWARDED_FOR ip: " ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
//System.out.println("X-Real-IP ip: " ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
//System.out.println("getRemoteAddr ip: " ip);
}
System.out.println("getRealIP2 获取客户端ip: " ip);
return ip;
}
/**
* 根据IP获取地理位置
*
* @param ip
* @return
*/
public static String getRealGeo(String ip) {
try {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("ip", ip);
paramMap.put("accessKey", "alibaba-inc");
String result1 = HttpUtil.post("http://ip.taobao.com/outGetIpInfo", paramMap);
Map jsonmap = (Map) JSON.parse(result1);
Map<String, String> datamap = (Map) JSON.parse(jsonmap.get("data").toString());
//System.out.println("判断下请求是否拿到数据了 (如果是0,那么完蛋,啥也没拿到):" datamap.size());
/*
System.out.println("ip is:" datamap.get("queryIp"));
System.out.println("国家 is:" datamap.get("country"));
System.out.println("省份 is:" datamap.get("region"));
System.out.println("市 is:" datamap.get("city"));
System.out.println("运营商 is:" datamap.get("isp"));
*/
return datamap.get("country") " " datamap.get("region") " " datamap.get("city") " " datamap.get("isp");
} catch (Exception e) {
}
return "";
}
/**
* @param request
*/
public static void check(HttpServletRequest request) {
String realIP = getRealIP(request);
String realGeo = getRealGeo(realIP);
System.out.println(realIP "--->" realGeo);
}
}
特殊说明: 以上文章,均是我实际操作,写出来的笔记资料,不会盗用别人文章!烦请各位,请勿直接盗用!转载记得标注来源!