java中IP地址判断所属区域(baidu接口)

来源:互联网 发布:直销矩阵制度图解 编辑:程序博客网 时间:2024/04/29 15:58

传入ip地址的字符串,返回所在市字符串,未查询到则return  “读取失败”

解析json使用  org.json.*


public static String getAddressByIP(String strIP) {try {URL url = new URL("http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip="+strIP);URLConnection conn = url.openConnection();BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));String line = null;StringBuffer result = new StringBuffer();while ((line = reader.readLine()) != null) {result.append(line);}reader.close();String ipAddr = result.toString();try {JSONObject obj1= new JSONObject(ipAddr);if("0".equals(obj1.get("status").toString())){JSONObject obj2= new JSONObject(obj1.get("content").toString());JSONObject obj3= new JSONObject(obj2.get("address_detail").toString());return obj3.get("city").toString();}else{return "读取失败";}} catch (JSONException e) {e.printStackTrace();return "读取失败";}} catch (IOException e) {return "读取失败";}}


0 0
原创粉丝点击