所需东西:高德地图的key
注意:这个key是 web服务的key 和js的key不是一个key(若没有则自行创建,创建教程在文末)
高德地图的api文档:https://lbs.amap.com/api/webservice/guide/api/ipconfig/
新建工具类如下:
调用时传IP地址即可获取对应城市编码或其他信息
package com.test.utils.gaode; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.test.commons.FailException; import java.io.*; import java.net.URL; import java.nio.charset.Charset; public class GdUtil { private static final String KEY = "17abf77d3c69e0d16c02e764f4fe6be4"; //web服务的key private static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } private static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { InputStream is = new URL(url).openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JSONObject json = JSONObject.parseObject(jsonText); return json; } finally { is.close(); } } public static String getCityCodeByIp(String ipAddress) { JSONObject json = null; String adCode = ""; try { json = readJsonFromUrl("http://restapi.amap.com/v3/ip?ip=" + ipAddress + "&key=" + KEY + ""); if ("0".equals(json.getString("status"))){ //调用异常时,抛出返回信息,以便分析(我会在错误层统一捕获并输出到error日志) throw new FailException("调用高德返回异常: " + json.toJSONString()); } } catch (IOException e) { e.printStackTrace(); throw new FailException("高德获取城市编码:", e); } adCode = json.getString("adcode"); //获取ip定位的城市编码(高德返回json如下,需要其他也可自行获取) return adCode; } public static void main(String[] args) { String s = GdUtil.getCityCodeByIp("60.191.12.10"); System.out.println(s); //330100 } }
高德返回json的格式如下(根据需要自行获取):
{
"status":"1",
"info":"OK",
"infocode":"10000",
"province":"浙江省",
"city":"杭州市",
"adcode":"330100",
"rectangle":"119.8824799,29.95931271;120.5552208,30.52048536"
}
此传入的ip为公网ip,所以我们还需要获取到请求者的公网ip:
package com.test.utils;
import javax.servlet.http.HttpServletRequest;
/**
* 请求对象 工具类
*/
public class RequestUtils {
/** * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; * * @param request * @return * @throws */ public final static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (String ip1 : ips) { String strIp = (String) ip1; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }
}
实际使用示例如下:
package com.test.web.common;
import com.alibaba.fastjson.JSONObject;
import com.test.utils.RequestUtils;
import com.test.utils.gaode.GdUtil;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
/**
*/
@RestController
@RequestMapping(value = "/api/core")
public class TestController {
private Logger log = Logger.getLogger(this.getClass());
@RequestMapping(value = "/test", method = RequestMethod.POST) public JsonResp test(@RequestBody JSONObject reqJson, HttpServletRequest request) {
log.debug("测试获取访问者的城市编码") JSONObject resJson = new JSONObject(); String ip = RequestUtils.getIpAddress(request); String adCode = GdUtil.getCityCodeByIp(ip); resJson.put("cityCode", adCode); return JsonResp.ok(resJson); }
}
通过以上方法便可以成功的获取到访问者的城市编码等信息了
高德地图获取key:可参考高德教程:https://lbs.amap.com/api/webservice/guide/create-project/get-key
1. 进入我的应用中
2. 若没有应用则创建新应用
3. 点击+号添加key
4. 填写信息,选择web服务
5. 保存提交
6. 在应用列表下的key列表中出现新添加的key
请求参数和响应参数说明(infocode状态码可参考:https://lbs.amap.com/api/webservice/guide/tools/info)