获取地址工具方法
@Slf4j
public class AddressUtils
{
public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
public static String getRealAddressByIP(String ip)
{
String address = "127.0.0.1";
// 内网不查询
if (IpUtils.internalIp(ip)){
return "内网IP";
}
if (Global.isAddressEnabled()){
String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
if (StringUtils.isEmpty(rspStr)) {
log.error("获取地理位置异常 {}", ip);
return address;
}
JSONObject obj;
try {
obj = JSON.unmarshal(rspStr, JSONObject.class);
JSONObject data = obj.getObj("data");
String region = data.getStr("region");
String city = data.getStr("city");
address = region + " " + city;
} catch (Exception e) {
log.error("获取地理位置异常 {}", ip);
}
}
return address;
}
/**
* 解析ip的地区信息
* @return com.aihuaiedu.common.core.domain.AjaxResult
*/
public static AjaxResult getAddress(String ip){
AjaxResult result = new AjaxResult();
if (IpUtils.internalIp(ip)) {
result.put("msg","内网IP");
result.put("code",500);
return result;
}
String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
if (StringUtils.isEmpty(rspStr)) {
log.error("清洗数据时 获取地理位置异常{}", ip);
result.put("code",500);
result.put("msg","获取地理位置异常");
return result;
}
JSONObject obj;
try {
Map<String, String> addr = new HashMap<>(5);
obj = JSON.unmarshal(rspStr, JSONObject.class);
JSONObject data = obj.getObj("data");
String region = data.getStr("region");
String city = data.getStr("city");
String region_id = data.getStr("region_id");
String city_id = data.getStr("city_id");
addr.put("region",region);
addr.put("city",city);
addr.put("region_id",region_id);
addr.put("city_id",city_id);
result.put("code",0);
result.put("area",addr);
} catch (Exception e) {
log.error("清洗数据时 获取地理位置异常 {}", e);
result.put("code",500);
result.put("msg","获取地理位置异常");
}
return result;
}
}