调用接口前需要在高德地图上申请一个key
/**
* 根据ip获取省份
* @param request
* @return
*/
private static JSONObject getProvince(HttpServletRequest request,String key){
RestTemplate restTemplate = new RestTemplate();
String ip = getIpAddr(request);
String url = "";
if (ip == null || "127.0.0.1".equals(ip)){
url = "https://restapi.amap.com/v3/ip?key=" + key;
}else {
url = "https://restapi.amap.com/v3/ip?ip="+ip+"&key=" + key;
}
ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
String body = forEntity.getBody();
JSONObject jsonObject = JSONObject.parseObject(body);
return jsonObject;
}
/**
* 获取IP地址
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
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地址】
最新推荐文章于 2024-05-06 18:16:21 发布