根据IP地址获取地理位置

之前做了一个天气预报,里面就用到了根据IP自动定位技术,今天就给大家分享一波:根据IP地址自动定位。

想要实现根据IP地址定位,你要做的事有如下两点:

第一:获取本机的IP地址

注意:这里指的是公网的IP地址,而不是局域网的IP地址,之前因为我是在学校,所以获取的本机IP是经过校园再分配的地址,不是公网的IP地址,导致定位失败。所以我们需要用到IP查询接口,之前用的是:http://ip.chinaz.com这个网址的接口,现在好像不能用了,于是又换了一个IP查询接口:http://whois.pconline.com.cn/

我们用URL资源定位符进行资源的拉取,然后利用正则表达式匹配我们想要的内容,这样便可以拿到我们本机的公网IP地址。

第二步:根据IP获取地理位置

当我们拿到本机的公网IP后,就可以使用接口来查询对应IP的地理位置了。我调用的是百度的ip定位api服务,详情参见:

http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm

下面是测试代码:


  
  
  1. package com.yc.weather;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.Reader;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.nio.charset.Charset;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. import org.json.JSONException;
  14. import org.json.JSONObject;
  15. /**
  16. * 根据ip获取地址
  17. *
  18. * @author jam
  19. *
  20. */
  21. public class Address {
  22. /**
  23. * 读取所有内容
  24. *
  25. * @param rd
  26. * @return
  27. * @throws IOException
  28. */
  29. private static String readAll(Reader rd) throws IOException {
  30. StringBuilder sb = new StringBuilder();
  31. int cp;
  32. while ((cp = rd.read()) != - 1) {
  33. sb.append(( char) cp);
  34. }
  35. return sb.toString();
  36. }
  37. /**
  38. * 拉取网页所有内容,并转化为Json格式
  39. *
  40. * @param url
  41. * @return
  42. * @throws IOException
  43. * @throws JSONException
  44. */
  45. public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
  46. InputStream is = new URL(url).openStream();
  47. try {
  48. BufferedReader rd = new BufferedReader( new InputStreamReader(is, Charset.forName( "UTF-8")));
  49. String jsonText = readAll(rd);
  50. JSONObject json = new JSONObject(jsonText);
  51. return json;
  52. } finally {
  53. is.close();
  54. }
  55. }
  56. public String getAddress() {
  57. String ip = "";
  58. // 这个网址似乎不能了用了
  59. // String chinaz = "http://ip.chinaz.com";
  60. // 改用了太平洋的一个网址
  61. String chinaz = "http://whois.pconline.com.cn/";
  62. StringBuilder inputLine = new StringBuilder();
  63. String read = "";
  64. URL url = null;
  65. HttpURLConnection urlConnection = null;
  66. BufferedReader in = null;
  67. try {
  68. url = new URL(chinaz);
  69. urlConnection = (HttpURLConnection) url.openConnection();
  70. // 如有乱码的,请修改相应的编码集,这里是 gbk
  71. in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), "gbk"));
  72. while ((read = in.readLine()) != null) {
  73. inputLine.append(read + "\r\n");
  74. }
  75. // System.out.println(inputLine.toString());
  76. } catch (MalformedURLException e) {
  77. e.printStackTrace();
  78. } catch (IOException e) {
  79. e.printStackTrace();
  80. } finally {
  81. if (in != null) {
  82. try {
  83. in.close();
  84. } catch (IOException e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. }
  89. // 这个是之前的正则表达式,
  90. // Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
  91. // 通过正则表达式匹配我们想要的内容,根据拉取的网页内容不同,正则表达式作相应的改变
  92. Pattern p = Pattern.compile( "显示IP地址为(.*?)的位置信息");
  93. Matcher m = p.matcher(inputLine.toString());
  94. if (m.find()) {
  95. String ipstr = m.group( 0);
  96. // 这里根据具体情况,来截取想要的内容
  97. ip = ipstr.substring(ipstr.indexOf( "为") + 2, ipstr.indexOf( "的") - 1);
  98. System.out.println(ip);
  99. }
  100. JSONObject json = null;
  101. String city = null;
  102. try {
  103. // 这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
  104. json = readJsonFromUrl( "http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip=" + ip);
  105. System.out.println(json);
  106. city = (((JSONObject) ((JSONObject) json.get( "content")).get( "address_detail")).get( "city")).toString();
  107. } catch (Exception e) {
  108. e.printStackTrace();
  109. }
  110. return city;
  111. }
  112. public static void main(String[] args) throws IOException, JSONException {
  113. Address Addr = new Address();
  114. String addr = Addr.getAddress();
  115. System.out.println(addr);
  116. }
  117. }

上面这个类只需要导入一个json的jar包就可以,在maven项目的pom.xml文件中添加如下依赖:


  
  
  1. <dependency>
  2. <groupId>org.json </groupId>
  3. <artifactId>json </artifactId>
  4. <version>20090211 </version>
  5. </dependency>

如果大家还不会使用maven,可以参考我的文章《maven入门笔记》,如果实在不想用maven的,可以去网上找json这个jar包,很容易找到的。

运行效果:

其实查询IP地址的接口和网站很多,大家随便百度都有,如果项目要上线并且长期使用的话,就需要找一家正规的公司进行合作了。

本来这个百度的IP定位API可以定位到街道甚至门牌号的,可能是因为我用的手机给电脑开的热点的原因,导致只能定位到市级,并且,这里我只取到了市级的位置,本来这个类我是用来查询天气时获取城市的一个类,只需要精确到市级就可以了,大家随便改改代码就可以查到自己想要的信息了,这里主要用到了json数据的解析。

OK,根据IP地址定位的经验分享到此告一段落,有时间我再给大家分享一下如何根据地理位置来查询天气。

文章属原创,如需引用,请注明出处,谢谢。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值