| | |
| | | package com.stylefeng.guns.modular.system.util; |
| | | import com.alibaba.fastjson.JSON; |
| | | import com.alibaba.fastjson.JSONArray; |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import com.stylefeng.guns.core.util.SpringContextHolder; |
| | | import org.apache.http.HttpEntity; |
| | | import org.apache.http.client.config.RequestConfig; |
| | | import org.apache.http.client.methods.CloseableHttpResponse; |
| | |
| | | } |
| | | |
| | | /** |
| | | * 获取GDKeyManager(非Spring环境下返回null,如main测试) |
| | | */ |
| | | private static GDKeyManager getKeyManager() { |
| | | try { |
| | | return SpringContextHolder.getBean(GDKeyManager.class); |
| | | } catch (Exception e) { |
| | | return null; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 根据地址查询经纬度 |
| | | * key次数用完时自动切换可用key重试 |
| | | * |
| | | * @param address |
| | | * @return |
| | | */ |
| | | public static JSONObject getLngAndLat(String address) { |
| | | JSONObject positionObj = new JSONObject(); |
| | | GDKeyManager keyManager = getKeyManager(); |
| | | |
| | | int maxAttempts = 5; |
| | | for (int i = 0; i < maxAttempts; i++) { |
| | | String key = keyManager != null ? keyManager.getKey() : GDKeyManager.FALLBACK_KEY; |
| | | try { |
| | | // 拼接请求高德的url |
| | | String url = "http://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + "ca723c3c8a78962a7751129ae035dc9d"; |
| | | String url = "http://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + key; |
| | | // 请求高德接口 |
| | | String result = sendHttpGet(url); |
| | | JSONObject resultJOSN = JSONObject.parseObject(result); |
| | | JSONObject resultJOSN = JSON.parseObject(result); |
| | | System.out.println("高德接口返回原始数据:"); |
| | | System.out.println(resultJOSN); |
| | | if (GDKeyManager.isWebKeyExhausted(resultJOSN)) { |
| | | if (keyManager != null) { |
| | | keyManager.reportExhausted(key); |
| | | } |
| | | continue; |
| | | } |
| | | JSONArray geocodesArray = resultJOSN.getJSONArray("geocodes"); |
| | | if (geocodesArray.size() > 0) { |
| | | if (geocodesArray != null && geocodesArray.size() > 0) { |
| | | String position = geocodesArray.getJSONObject(0).getString("location"); |
| | | String[] lngAndLat = position.split(","); |
| | | String longitude = lngAndLat[0]; |
| | |
| | | positionObj.put("longitude", longitude); |
| | | positionObj.put("latitude", latitude); |
| | | } |
| | | geocodesArray.getJSONObject(0).getString("location"); |
| | | |
| | | break; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | return positionObj; |
| | | } |
| | | |