/**
* 查询ip所在地址工具类
* 参考百度地图官方文档:https://lbs.baidu.com/index.php?title=webapi/ip-api
* @author yqf
* @date 2022-09-24
*/
@Slf4j
public class IpUtil {
private static final StringHTTPS ="https://api.map.baidu.com/location/ip";//百度地图通过ip获取地址,免费
private static final StringAK ="vOqYxqFvgf0HqSiPFzHtVUvy7tKg8CPP";//开发者密钥,可在API控制台申请获得
/**
* 获取登录用户的IP地址
*
* @param request
* @return
*/
public static StringgetIpAddr(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();
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip ="127.0.0.1";
}
if (ip.split(",").length >1) {
ip = ip.split(",")[0];
}
return ip;
}
/**
* 通过IP获取地址(需要联网,调用淘宝的IP库)
*
* @param ip
* @return
*/
public static StringgetIpInfo(String ip) {
if ("127.0.0.1".equals(ip)) {
ip ="127.0.0.1";
}
String info ="";
try {
URL url =new URL(HTTPS+"?ak="+AK+"&ip="+ip);
HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
htpcon.setRequestMethod("GET");
htpcon.setDoOutput(true);
htpcon.setDoInput(true);
htpcon.setUseCaches(false);
InputStream in = htpcon.getInputStream();
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(in));
StringBuffer temp =new StringBuffer();
String line = bufferedReader.readLine();
while (line !=null) {
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
JSONObject obj = (JSONObject) JSON.parse(temp.toString());
JSONObject content = obj.getJSONObject("content");
info += content.getString("address") +" ";
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (ProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return info;
}
}
//调用类
/**
* 查询ip所在地址
*/
@GetMapping("/queryIpAddress")
public ResultqueryIpAddress(HttpServletRequest request) {
String ip= IpUtil.getIpAddr(request);
if(ObjectUtils.isEmpty(ip)){
return Result.error("ip获取失败");
}
String address=IpUtil.getIpInfo(ip);
if(ObjectUtils.isEmpty(address)){
return Result.error("暂无归属地");
}else {
return Result.success("归属地查询成功",address);
}
}