Java根据地名获取所在省,市,县
设计思想,首先调用百度地图API查询地名对应的经度和纬度,然后根据经度和纬度查询所在省,市,县
package com.lq; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONObject; public class Test { /** * 百度地图通过经纬度来获取地址,传入参数纬度lat、经度lng * @param lat * @param lng * @return */ public static String getCity(String lat, String lng) { JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result").getJSONObject("addressComponent"); String province,city,district; province=obj.getString("province"); city=obj.getString("city"); district=obj.getString("district"); if(province.equals(city)) { System.out.println(city+district); return city+district; } else { System.out.println(province+city+district); return province+city+district; } } public static JSONObject getLocationInfo(String lat, String lng) { String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=ltGIgbvqAEeZFjyOhVFS0jVmE1HpRn9K" + "&output=json&coordtype=wgs84ll&location="+ lat + "," + lng ; JSONObject obj = JSONObject.fromObject(loadJSON(url)); return obj; } /** * 百度地图通过地址来获取经纬度,传入参数address * @param address * @return */ public static Map<String,Double> getLngAndLat(String address) { Map<String,Double> map=new HashMap<String, Double>(); String url = "http://api.map.baidu.com/geocoding/v3/?address="+address+"&output=json&ak=ltGIgbvqAEeZFjyOhVFS0jVmE1HpRn9K" + "&coordtype=wgs84ll"; JSONObject obj = JSONObject.fromObject(loadJSON(url)); //System.out.println(obj); if(obj.get("status").toString().equals("0")) { double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng"); double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat"); map.put("lng", lng); map.put("lat", lat); System.out.println("经度:" + lng + "--- 纬度:" + lat); }else{ map.put("lng", 0.00); map.put("lat", 0.00); } return map; } public static String loadJSON (String url) { StringBuilder json = new StringBuilder(); try { URL oracle = new URL(url); URLConnection yc = oracle.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine = null; while ( (inputLine = in.readLine()) != null) { json.append(inputLine); } in.close(); } catch (Exception e) { e.printStackTrace(); } return json.toString(); } public static void main(String[] args) { String area="北京市水科学技术研究院"; Map<String,Double> map=new HashMap<String, Double>(); map=getLngAndLat(area); String lat=""+map.get("lat"); String lng=""+map.get("lng"); getCity(lat, lng); } }
运行截图:
python获取本机的外网IP:
import requests import re def getIP(): headers = {} headers['User-Agent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36" response = requests.get('http://txt.go.sohu.com/ip/soip',headers=headers) html = response.text reGET = re.compile(r'\d+.\d+.\d+.\d+.').findall(html) for i in reGET: print('外网地址: %s'%i) getIP()