利用百度地圖API進行根據ip定位城市

根據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簽字,方法如下:

這裏給出別人的方法連接:https://blog.csdn.net/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 "本地登錄";
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章