所需東西:高德地圖的key javascript
注意:這個key是 web服務的key 和js的key不是一個key(若沒有則自行建立,建立教程在文末)java
高德地圖的api文檔:https://lbs.amap.com/api/webservice/guide/api/ipconfig/ web
新建工具類以下:apache
調用時傳IP地址便可獲取對應城市編碼或其餘信息json
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的格式以下(根據須要自行獲取):api
{
"status":"1",
"info":"OK",
"infocode":"10000",
"province":"浙江省",
"city":"杭州市",
"adcode":"330100",
"rectangle":"119.8824799,29.95931271;120.5552208,30.52048536"
}
此傳入的ip爲公網ip,因此咱們還須要獲取到請求者的公網ip:app
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; }
}
實際使用示例以下:ide
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)