通过百度接口获取IP所属地

 /**
  * @Description getAddressByBD
  * @Explain 通过百度接口获取IP所属地
  **/
public static String getAddressByBD(String strIP) throws JSONException {
        try {
            URL url = new URL("http://opendata.baidu.com/api.php?query=" + strIP + "&co=&resource_id=6006&t=1433920989928&ie=utf8&oe=utf-8&format=json");
            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();
            JSONObject jsStr = new JSONObject(result.toString());
            JSONArray jsData = (JSONArray) jsStr.get("data");
            if (jsData != null && jsData.length() > 0) {
                JSONObject data = (JSONObject) jsData.get(0);
                return (String) data.get("location");
            } else {
                return "不可识别的IP地址";
            }
        } catch (IOException e) {
            return "读取失败";
        }
 }

你可能感兴趣的:(Java多线程)