根据ip进行定位城市,本次利用的是根据百度地图API进行定位.网上也有其他的方法.本次就将我自己写的东西总结一下:
一.首先获取ip地址
public static String getReqIp(HttpServletRequest request) throws IOException {String ip = request.getHeader("x-forwarded-for");if (ip != null) {if (ip.indexOf(',') == -1) {return ip;}return ip.split(",")[0];}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();}String city=LocationByIp.getlocation(ip);//此处是有一个方法根据ip进行定位城市return ip+"+"+city;//返回城市和ip地址}
二.调用百度地图API进行定位城市
1.首先要获取sncal签字,方法如下:
这里给出别人的方法连接:/weixin_39549656/article/details/80096456
这里的sncal是根据输入的位置和ip进行sncal算法进行计算得出sn签字.其中公司的AK是必须存在的!
2.若不输入位置,就是可以根据ip进行城市定位.
对上面的列子获取到的参数进行处理
String html = EntityUtils.toString(entity);// 把响应实体转成文本JSONObject jsondata=JSONObject.parseObject(html);//将响应转换成json数组Object content=jsondata.get("content");//获取内容
if (content!=null){JSONObject addressdetail=JSONObject.parseObject(content.toString());//将响应转换成json数组并获取地址信息Object dizhi=addressdetail.get("address_detail");//获取地址详细内容JSONObject dizhidetail=JSONObject.parseObject(dizhi.toString());//将响应转换成json数组//String province=dizhidetail.get("province").toString();//安徽省String city=dizhidetail.get("city").toString();//合肥市return city;}else{return "本地登录";}