1 前言
略
2 代码
public class AddressUtil { private static String key = "your api key“; private static String urlByIp = "http://apis.map.qq.com/ws/location/v1/ip?key=" + key; public static Map<String, String> getLocation(String ip) { String realUrl = urlByIp; if (ip != null) { realUrl = urlByIp + "&ip=" + ip; } Map<String, String> map = new HashMap<>(); String resp = RequestUtils.get(realUrl); // { // "status": 0, // "message": "query ok", // "result": { // "ip": "240e:37a:4469:d600:1ce4:4e71:8fe1:86f5", // "location": { // "lat": 24.87389, // "lng": 118.67587 // }, // "ad_info": { // "nation": "中国", // "province": "XX省", // "city": "XX市", // "district": "", // "adcode": 110500 // } // } // } JSONObject respJson = JSON.parseObject(resp); if (respJson != null) { int status = respJson.getInteger("status"); if (status == 0) { JSONObject resultJson = respJson.getJSONObject("result"); JSONObject location = resultJson.getJSONObject("location"); map.put("location", location.getString("lat") + "," + location.getString("lng")); JSONObject ad_info = resultJson.getJSONObject("ad_info"); String province = ad_info.getString("province"); String city = ad_info.getString("city"); map.put("province", province); map.put("city", city); return map; } } return null; } } //RequestUtils.java public static String get(String url) { ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); String resp = responseEntity.getBody(); return resp; }
3 小结
略