java实现根据ip定位地理位置(调用百度接口)
这里用的是若依的springboot框架,框架里自带的获取地理位置接口是调用的淘宝的,已经不可用。于是找到哦百度接口实现。
调用百度接口:
public class AddressUtils { private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); public static final String IP_URL = "http://api.map.baidu.com/location/ip?ak=xQ3jYoPgpIsGxFZ8vtWGbtsY07**8&coor=bd09ll"; public static String getRealAddressByIP(String ip) { String address = "XX XX"; // 内网不查询 if (IpUtils.internalIp(ip)) { return "内网IP"; } 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 content = obj.getObj("content"); // JSONObject address_detail = content.getObj("address_detail"); String addresses = content.getStr("address"); address = addresses ; } catch (Exception e) { log.error("获取地理位置异常 {}", ip); } return address; } public static void main(String[] args) { System.out.println(getRealAddressByIP("61.158.148.101")); } }
本文原创,转载必追究版权。