使用百度定位Api获取当前用户登录地址
最近在做一个商城项目,客户想把网站做成类似于美团的效果,切换地区时,内容也跟随变化.这就要首先解决根据用户id获得地址的问题,最终决定使用百度定位(不适用于搭建反向代理的项目)
String url = request.getRemoteAddr(); // url = "58.56.23.118"; //本地代码测试ip,使用本地公网 // 这里调用百度的ip定位api服务 详见 ak需要申请 // http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm org.json.JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=马赛克部分&ip=" + url); // json.get("content")).get("address")); // status状态为2,表示没有获取到地区信息 if ((Integer) json.get("status") != 2) { /* * Object adress = ((org.json.JSONObject) * json.get("content")) .get("address"); */ // "address_detail":{"province":"山东省","city":"济南市","street":"","district":"","street_number":"","city_code":288},"address":"山东省济南市"," Object adress = null; if(json.get("content") != null && ((org.json.JSONObject)json.get("content")).get("address_detail") != null) { adress = ((JSONObject) ((org.json.JSONObject) json .get("content")).get("address_detail")).get("city"); String areaName = (String) adress; //获取到市级城市名称 //request.getSession().setAttribute("area_name", areaName); Map params = new HashMap(); params.put("areaName", areaName); List<Area> areas = this.areaService .query("select obj from Area obj where obj.areaName=:areaName", params, -1, -1); if (areas.size() > 0 && areas != null) { Area area = areas.get(0); area_id = area.getId().longValue(); request.getSession().setAttribute("area_id", area_id); request.getSession() .setAttribute("area_name", areaName); mv.addObject("area_id", area_id); mv.addObject("adress", adress); } } else { //mv.addObject("adress", "中国大区"); area_id = null; request.getSession().setAttribute("area_name", "中国大区"); }
上述代码有原项目代码, 定位精确到市级,获取不到地址时默认中国大区,除定位部分外其他不用理会.
上述代码用到的工具类 readJsonFromUrl()
public static org.json.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); org.json.JSONObject json = new org.json.JSONObject(jsonText); return json; } finally { is.close(); // System.out.println("同时 从这里也能看出 即便return了,仍然会执行finally的!"); } }
功能完成时,登录网站首页显示效果: