【用百度获取IP地址经纬度】

下面我们举例说明一下关于利用百度获取IP地址经纬度的方法:

  /**

  * 获取指定IP对应的经纬度(为空返回当前机器经纬度)

  *

  * @param ip

  * @return

  */

  public static String[] getIPXY(String ip) {

  String ak = "百度申请的Key";

  if (null == ip) {

  ip = "";

  }

  try {

  URL url = new URL("http://api.map.baidu.com/location/ip?ak=" + ak

  + "&ip=" + ip + "&coor=bd09ll");

  InputStream inputStream = url.openStream();

  InputStreamReader inputReader = new InputStreamReader(inputStream);

  BufferedReader reader = new BufferedReader(inputReader);

  StringBuffer sb = new StringBuffer();

  String str;

  do {

  str = reader.readLine();

  sb.append(str);

  } while (null != str);

  str = sb.toString();

  if (null == str || str.isEmpty()) {

  return null;

  }

  // 获取坐标位子

  int index = str.indexOf("point");

  int end = str.indexOf("}}", index);

  if (index == -1 || end == -1) {

  return null;

  }

  str = str.substring(index - 1, end + 1);

  if (null == str || str.isEmpty()) {

  return null;

  }

  String[] ss = str.split(":");

  if (ss.length != 4) {

  return null;

  }

  String x = ss[2].split(",")[0];

  String y = ss[3];

  x = x.substring(x.indexOf("\"") + 1, x.indexOf("\"", 1));

  y = x.substring(y.indexOf("\"") + 1, y.indexOf("\"", 1));

  return new String[] { x, y };

  } catch (MalformedURLException e) {

  e.printStackTrace();

  } catch (IOException e) {

  e.printStackTrace();

  }

  return null;

  }

posted @ 2013-09-30 17:11  豆豆逗逗  阅读(302)  评论(0编辑  收藏  举报