统计
  • 建站日期:2019-12-01
  • 文章总数:2331 篇
  • 评论总数:2159 条
  • 分类总数:22 个
  • 最后更新:4月1日
文章 未分类

java 根据IP地址获取地理位置

程序员阿鑫
首页 未分类 正文


java根据IP地址获取地理位置
-程序员阿鑫-带你一起秃头
-第1
张图片

java根据IP地址获取地理位置 -程序员阿鑫-带你一起秃头 -第1 张图片

java 根据IP地址获取地理位置

一、第三方API

ps:下面参数ip: 218.192.3.42 用于测试

  1. 淘宝API:http://ip.taobao.com/service/getIpInfo.php?ip=218.192.3.42
  2. 新浪API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.192.3.42
  3. pconline API:http://whois.pconline.com.cn/
  4. 百度API:http://api.map.baidu.com/location/ip?ip=218.192.3.42

二、工具类

AddressUtils.java

  1. import java.io.BufferedReader;
  2. import java.io.DataOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. /**
  9. * 根据IP地址获取详细的地域信息
  10. * 淘宝API : http://ip.taobao.com/service/getIpInfo.php?ip=218.192.3.42
  11. * 新浪API : http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.192.3.42
  12. * @File AddressUtils.java
  13. * @Package org.gditc.weicommunity.util
  14. * @Description TODO
  15. * @Copyright Copyright © 2014
  16. * @Site https://github.com/Cryhelyxx
  17. * @Blog http://blog.csdn.net/Cryhelyxx
  18. * @Email cryhelyxx@gmail.com
  19. * @Company GDITC
  20. * @Date 2014年11月6日 下午1:46:37
  21. * @author Cryhelyxx
  22. * @version 1.0
  23. */
  24. public class AddressUtils {
  25. /**
  26. *
  27. * @param content
  28. * 请求的参数 格式为:name=xxx&pwd=xxx
  29. * @param encoding
  30. * 服务器端请求编码。如GBK,UTF-8等
  31. * @return
  32. * @throws UnsupportedEncodingException
  33. */
  34. public static String getAddresses(String content, String encodingString)
  35. throws UnsupportedEncodingException {
  36. // 这里调用淘宝API
  37. String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
  38. // 从http://whois.pconline.com.cn取得IP所在的省市区信息
  39. String returnStr = getResult(urlStr, content, encodingString);
  40. if (returnStr != null) {
  41. // 处理返回的省市区信息
  42. System.out.println("(1) unicode转换成中文前的returnStr : " + returnStr);
  43. returnStr = decodeUnicode(returnStr);
  44. System.out.println("(2) unicode转换成中文后的returnStr : " + returnStr);
  45. String[] temp = returnStr.split(",");
  46. if(temp.length<3){
  47. return "0";//无效IP,局域网测试
  48. }
  49. return returnStr;
  50. }
  51. return null;
  52. }
  53. /**
  54. * @param urlStr
  55. * 请求的地址
  56. * @param content
  57. * 请求的参数 格式为:name=xxx&pwd=xxx
  58. * @param encoding
  59. * 服务器端请求编码。如GBK,UTF-8等
  60. * @return
  61. */
  62. private static String getResult(String urlStr, String content, String encoding) {
  63. URL url = null;
  64. HttpURLConnection connection = null;
  65. try {
  66. url = new URL(urlStr);
  67. connection = (HttpURLConnection) url.openConnection();// 新建连接实例
  68. connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒
  69. connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒
  70. connection.setDoOutput(true);// 是否打开输出流 true|false
  71. connection.setDoInput(true);// 是否打开输入流true|false
  72. connection.setRequestMethod("POST");// 提交方法POST|GET
  73. connection.setUseCaches(false);// 是否缓存true|false
  74. connection.connect();// 打开连接端口
  75. DataOutputStream out = new DataOutputStream(connection
  76. .getOutputStream());// 打开输出流往对端服务器写数据
  77. out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
  78. out.flush();// 刷新
  79. out.close();// 关闭输出流
  80. BufferedReader reader = new BufferedReader(new InputStreamReader(
  81. connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
  82. // ,以BufferedReader流来读取
  83. StringBuffer buffer = new StringBuffer();
  84. String line = "";
  85. while ((line = reader.readLine()) != null) {
  86. buffer.append(line);
  87. }
  88. reader.close();
  89. return buffer.toString();
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. } finally {
  93. if (connection != null) {
  94. connection.disconnect();// 关闭连接
  95. }
  96. }
  97. return null;
  98. }
  99. /**
  100. * unicode 转换成 中文
  101. *
  102. * @author fanhui 2007-3-15
  103. * @param theString
  104. * @return
  105. */
  106. public static String decodeUnicode(String theString) {
  107. char aChar;
  108. int len = theString.length();
  109. StringBuffer outBuffer = new StringBuffer(len);
  110. for (int x = 0; x < len;) {
  111. aChar = theString.charAt(x++);
  112. if (aChar == '') {
  113. aChar = theString.charAt(x++);
  114. if (aChar == 'u') {
  115. int value = 0;
  116. for (int i = 0; i < 4; i++) {
  117. aChar = theString.charAt(x++);
  118. switch (aChar) {
  119. case '0':
  120. case '1':
  121. case '2':
  122. case '3':
  123. case '4':
  124. case '5':
  125. case '6':
  126. case '7':
  127. case '8':
  128. case '9':
  129. value = (value << 4) + aChar - '0';
  130. break;
  131. case 'a':
  132. case 'b':
  133. case 'c':
  134. case 'd':
  135. case 'e':
  136. case 'f':
  137. value = (value << 4) + 10 + aChar - 'a';
  138. break;
  139. case 'A':
  140. case 'B':
  141. case 'C':
  142. case 'D':
  143. case 'E':
  144. case 'F':
  145. value = (value << 4) + 10 + aChar - 'A';
  146. break;
  147. default:
  148. throw new IllegalArgumentException(
  149. "Malformed encoding.");
  150. }
  151. }
  152. outBuffer.append((char) value);
  153. } else {
  154. if (aChar == 't') {
  155. aChar = 't';
  156. } else if (aChar == 'r') {
  157. aChar = 'r';
  158. } else if (aChar == 'n') {
  159. aChar = 'n';
  160. } else if (aChar == 'f') {
  161. aChar = 'f';
  162. }
  163. outBuffer.append(aChar);
  164. }
  165. } else {
  166. outBuffer.append(aChar);
  167. }
  168. }
  169. return outBuffer.toString();
  170. }
  171. // 测试
  172. public static void main(String[] args) {
  173. AddressUtils addressUtils = new AddressUtils();
  174. // 测试ip 219.136.134.157 中国=华南=广东省=广州市=越秀区=电信
  175. String ip = "122.49.20.247";
  176. String address = "";
  177. try {
  178. address = addressUtils.getAddresses("ip="+ip, "utf-8");
  179. } catch (UnsupportedEncodingException e) {
  180. // TODO Auto-generated catch block
  181. e.printStackTrace();
  182. }
  183. System.out.println(address);
  184. // 输出结果为:广东省,广州市,越秀区
  185. }
  186. }

三、 测试方法

下面采用单元测试

  1. @Test
  2. public void getAddressByIp() throws Exception {
  3. // 参数ip
  4. String ip = "219.136.134.157";
  5. // json_result用于接收返回的json数据
  6. String json_result = null;
  7. try {
  8. json_result = AddressUtils.getAddresses("ip=" + ip, "utf-8");
  9. } catch (UnsupportedEncodingException e) {
  10. e.printStackTrace();
  11. }
  12. JSONObject json = JSONObject.fromObject(json_result);
  13. System.out.println("json数据: " + json);
  14. String country = JSONObject.fromObject(json.get("data")).get("country").toString();
  15. String region = JSONObject.fromObject(json.get("data")).get("region").toString();
  16. String city = JSONObject.fromObject(json.get("data")).get("city").toString();
  17. String county = JSONObject.fromObject(json.get("data")).get("county").toString();
  18. String isp = JSONObject.fromObject(json.get("data")).get("isp").toString();
  19. String area = JSONObject.fromObject(json.get("data")).get("area").toString();
  20. System.out.println("国家: " + country);
  21. System.out.println("地区: " + area);
  22. System.out.println("省份: " + region);
  23. System.out.println("城市: " + city);
  24. System.out.println("区/县: " + county);
  25. System.out.println("互联网服务提供商: " + isp);
  26. String address = country + "/";
  27. address += region + "/";
  28. address += city + "/";
  29. address += county;
  30. System.out.println(address);
  31. }

四、 打印结果

下面是eclipse控制台的打印结果
(1) unicode转换成中文前的

  1. returnStr : {"code":0,"data":{"country":"u4e2du56fd","country_id":"CN","area":"u534eu5357","area_id":"800000","region":"u5e7fu4e1cu7701","region_id":"440000","city":"u5e7fu5ddeu5e02","city_id":"440100","county":"u8d8au79c0u533a","county_id":"440104","isp":"u7535u4fe1","isp_id":"100017","ip":"219.136.134.157"}}

(2) unicode转换成中文后的

  1. returnStr : {"code":0,"data":{"country":"中国","country_id":"CN","area":"华南","area_id":"800000","region":"广东省","region_id":"440000","city":"广州市","city_id":"440100","county":"越秀区","county_id":"440104","isp":"电信","isp_id":"100017","ip":"219.136.134.157"}}
  1. json数据: {"code":0,"data":{"country":"中国","country_id":"CN","area":"华南","area_id":"800000","region":"广东省","region_id":"440000","city":"广州市","city_id":"440100","county":"越秀区","county_id":"440104","isp":"电信","isp_id":"100017","ip":"219.136.134.157"}}

国家: 中国
地区: 华南
省份: 广东省
城市: 广州市
区/县: 越秀区
互联网服务提供商: 电信
中国/广东省/广州市/越秀区

版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。
版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!

-- 展开阅读全文 --
这篇文章最后更新于2022-10-15,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
java中try(){}的使用简要说明
« 上一篇
【java.lang.OutOfMemoryError:GC overhead limit exceeded异常解决方法】
下一篇 »

发表评论


扫一扫,支付10
支付完成后,请等待5秒左右。手机请点此支付!