1.获取互联网访问IP信息

一般获取互联网访问的IP的相关信息一般都是收费接口,免费的接口不多,我使用到一个接口如下:

  

  1. http://ip.taobao.com/service/getIpInfo.php?ip=139.189.109.174

这个是淘宝的接口,直接可以查询对应的IP信息,免费使用哦。在Java程序里可以直接封装调用。

对封装获取IP的地址的方法代码如下:

HttpRequestUtils.java

  1. package com.seezoon.framework.common.http;
  2.  
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9.  
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.HttpStatus;
  12. import org.apache.http.NameValuePair;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.CloseableHttpResponse;
  15. import org.apache.http.client.methods.HttpGet;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.client.methods.HttpRequestBase;
  18. import org.apache.http.client.utils.URIBuilder;
  19. import org.apache.http.entity.ContentType;
  20. import org.apache.http.entity.StringEntity;
  21. import org.apache.http.message.BasicNameValuePair;
  22. import org.apache.http.util.EntityUtils;
  23. import org.slf4j.Logger;
  24. import org.slf4j.LoggerFactory;
  25. import org.springframework.util.Assert;
  26. import org.springframework.util.StopWatch;
  27.  
  28. import com.alibaba.fastjson.JSON;
  29. import com.seezoon.framework.common.context.exception.ServiceException;
  30.  
  31. /**
  32. * 对性能和参数要求敏感,需要自行利用 HttpPoolClient 对象自行构造
  33. *
  34. * @author hdf 2018年4月23日
  35. */
  36. public class HttpRequestUtils {
  37.  
  38. /**
  39. * 日志对象
  40. */
  41. private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
  42.  
  43. private static String DEFAULT_CHARSET = "UTF-8";
  44.  
  45. private static HttpPoolClient defaultHttpPoolClient = new HttpPoolClient();
  46.  
  47. public static <T> T doGet(String url, Map<String, String> params, Class<T> clazz) {
  48. return JSON.parseObject(doGet(url, params), clazz);
  49. }
  50.  
  51. public static <T> T doPost(String url, Map<String, String> params, Class<T> clazz) {
  52. return JSON.parseObject(doPost(url, params), clazz);
  53. }
  54.  
  55. public static <T> T postJson(String url, Map<String, String> params, Class<T> clazz) {
  56. return JSON.parseObject(postJson(url, params), clazz);
  57. }
  58.  
  59. public static String postJson(String url, Map<String, String> params) {
  60. HttpPost httpPost = new HttpPost(url);
  61. httpPost.setEntity(new StringEntity(JSON.toJSONString(params), ContentType.APPLICATION_JSON));
  62. return execute(httpPost);
  63. }
  64.  
  65. public static String postXml(String url,String content) {
  66. HttpPost httpPost = new HttpPost(url);
  67. httpPost.setEntity(new StringEntity(content, ContentType.create("application/xml", "UTF-8")));
  68. return execute(httpPost);
  69. }
  70. public static String doGet(String url, Map<String, String> params) {
  71. Assert.hasLength(url, "请求地址为空");
  72. try {
  73. URIBuilder builder = new URIBuilder(url);
  74. builder.setParameters(getNameValuePair(params));
  75. HttpGet httpGet = new HttpGet(builder.toString());
  76. String result = execute(httpGet);
  77. return result;
  78. } catch (Exception e) {
  79. throw new ServiceException(e);
  80. }
  81. }
  82.  
  83. public static String doPost(String url, Map<String, String> params) {
  84. HttpPost httpPost = new HttpPost(url);
  85. httpPost.setEntity(getUrlEncodedFormEntity(params));
  86. return execute(httpPost);
  87. }
  88.  
  89. public static String execute(HttpRequestBase request) {
  90. StopWatch watch = new StopWatch();
  91. watch.start();
  92. CloseableHttpResponse response = null;
  93. try {
  94. response = defaultHttpPoolClient.execute(request);
  95. watch.stop();
  96. String requestURI = request.getURI().toString();
  97. logger.debug("http client:{} comleted use {} ms",requestURI,watch.getTotalTimeMillis());
  98. int status = response.getStatusLine().getStatusCode();
  99. if (HttpStatus.SC_OK == status) {// 成功
  100. HttpEntity entity = response.getEntity();
  101. if (null != entity) {
  102. String result = EntityUtils.toString(entity, DEFAULT_CHARSET);
  103. EntityUtils.consume(entity);
  104. return result;
  105. } else {
  106. throw new ServiceException("请求无数据返回");
  107. }
  108. } else {
  109. throw new ServiceException("请求状态异常失败");
  110. }
  111. } catch (Exception e) {
  112. throw new ServiceException(request.getURI().toString() + "请求失败", e);
  113. } finally {
  114. if (null != response) {
  115. try {
  116. response.close();
  117. } catch (IOException e) {
  118. logger.error("CloseableHttpResponse close error", e);
  119. }
  120. }
  121. }
  122. }
  123.  
  124. private static UrlEncodedFormEntity getUrlEncodedFormEntity(Map<String, String> params) {
  125. UrlEncodedFormEntity entity = null;
  126. try {
  127. entity = new UrlEncodedFormEntity(getNameValuePair(params), DEFAULT_CHARSET);
  128. } catch (UnsupportedEncodingException e) {
  129. }
  130. return entity;
  131. }
  132.  
  133. private static List<NameValuePair> getNameValuePair(Map<String, String> params){
  134. List<NameValuePair> list = new ArrayList<NameValuePair>();
  135. if (null != params && !params.isEmpty()) {
  136. for (Entry<String, String> entry : params.entrySet()) {
  137. list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  138. }
  139. }
  140. return list;
  141. }
  142.  
  143. public static void shutDown() {
  144. defaultHttpPoolClient.shutdown();
  145. }
  146. }

ServiceException.java

  1. package com.seezoon.framework.common.context.exception;
  2.  
  3. /**
  4. * 自定义异常方便后续扩展
  5. *
  6. * @author hdf 2018年4月20日
  7. */
  8. public class ServiceException extends RuntimeException {
  9.  
  10. public ServiceException() {
  11. super();
  12. // TODO Auto-generated constructor stub
  13. }
  14.  
  15. public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
  16. super(message, cause, enableSuppression, writableStackTrace);
  17. // TODO Auto-generated constructor stub
  18. }
  19.  
  20. public ServiceException(String message, Throwable cause) {
  21. super(message, cause);
  22. // TODO Auto-generated constructor stub
  23. }
  24.  
  25. public ServiceException(String message) {
  26. super(message);
  27. // TODO Auto-generated constructor stub
  28. }
  29.  
  30. public ServiceException(Throwable cause) {
  31. super(cause);
  32. // TODO Auto-generated constructor stub
  33. }
  34.  
  35. }

调用使用方法如下:

  1. if (StringUtils.isNotEmpty(ip)) {
  2. String ipInfo = HttpRequestUtils.doGet("http://ip.taobao.com/service/getIpInfo.php", Maps.newHashMap("ip",ip));
  3. if (StringUtils.isNotEmpty(ipInfo)) {
  4. JSONObject parseObject = JSON.parseObject(ipInfo);
  5. if (parseObject.containsKey("data")) {
  6. JSONObject data = parseObject.getJSONObject("data");
  7. System.out.println(data.getString("region") + data.getString("city"));
  8. }
  9. }
  10. }

更详细的写在了CSDN上:https://blog.csdn.net/lr393993507/article/details/82345614

通过淘宝接口免费获取IP地址信息的更多相关文章

  1. C#根据淘宝接口网址获取客户端访问IP和网络运营商

    网络运营商会为每台联网的电脑分配公网IP,如何获取它们?? 话不多说直接上代码: using System; using System.Collections.Generic; using Syste ...

  2. 淘宝接口实现ip归属地查询

    <?php header('content-type:text/html;charset=utf-8'); /*获取当前ip归属地 调用淘宝接口 */ function get_ip_place ...

  3. [Xcode 实际操作]八、网络与多线程-(11)使用同步Post方式查询IP地址信息

    目录:[Swift]Xcode实际操作 本文将演示如何通过Post请求,同步获取IP地址信息. 一旦发送同步请求,程序将停止用户交互,直至服务器返回数据. 在项目导航区,打开视图控制器的代码文件[Vi ...

  4. [Xcode 实际操作]八、网络与多线程-(12)使用异步Post方式查询IP地址信息

    目录:[Swift]Xcode实际操作 本文将演示如何通过Post请求,异步获取IP地址信息. 异步请求与同步请求相比,不会阻塞程序的主线程,而会建立一个新的线程. 在项目导航区,打开视图控制器的代码 ...

  5. PHP通过访问第三方接口,根据IP地址获取所在城市

    <?php header('Content-Type:text/html;Charset=utf-8'); /** * 获取IP地址 * * @return string */ function ...

  6. php获取ip地址所在的地理位置的实现

    1,通过腾讯或者新浪提供的接口来获取(新浪和腾讯类似) <?php     function getIPLocation($queryIP){      $url = 'http://ip.qq ...

  7. 获取IP地址的几种方法

    根据ip获取地址的几种方法 1.调用新浪IP地址库 <script type="text/javascript" src="js/jquery.js"&g ...

  8. 淘宝接口 TopAPi

    演示一下调用淘宝的接口,让大家心里有个数, 很简单,新建一个工程,拖一个IDHttp,Button和Memo到窗体上去 然后在这个Button的OnClick事件中写入如下代码: [delphi] v ...

  9. PHP学习笔记13淘宝接口开发一例(tmall.items.discount.search),PHP

    程序设计,因为接口是有请求次数限制的,正式接口也只有2W次每天的请求次数,所以我们需要把从接口返回的数据缓存起来. 采用的接口是http://api.taobao.com/apidoc/api.htm ...

随机推荐

  1. Swift - 用UIScrollView实现视差动画效果

    Swift - 用UIScrollView实现视差动画效果 效果 源码 https://github.com/YouXianMing/Swift-Animations // // MoreInfoVi ...

  2. curl win

    curl -H "tocken: 123456789"   -H "userName: admin"  http://39.18.10.2/log/v1/err ...

  3. Toast的用法(可以设置显示时间,自定义布局的,线程中的Toast)

           自定义的Toast类 布局文件 <?xml version="1.0" encoding="utf-8"?> <LinearLa ...

  4. Orchard 前台权限与自定义权限

    一:关于前台权限 1:只允许自己看到 首先,我们需要确定在 Role 设置页面,用户所对应的 View Page by others 和 View all content 未被选中.备注,我们首先和得 ...

  5. SVG渲染顺序及z轴显示问题(zIndex)

    SVG是严格按照定义元素的顺序来渲染的,这个与HTML靠z-index值来控制分层不一样. 在SVG中,写在前面的元素先被渲染,写在后面的元素后被渲染.后渲染的元素会覆盖前面的元素,虽然有时候受透明度 ...

  6. linux中的通配符、元字符、转义符

    linux中的通配符.元字符.转义符 linux中的通配符元字符转义符 shell命令的构成 通配符 元字符meta 转义符 example reference shell命令的构成 每条linux命 ...

  7. http://download.csdn.net/detail/yanzi1225627/6548337

    [2013.9.8网络首发]导入Android4.2源码里的Gallery2和Camera模块至Eclipse全过程 上次导入的时候是新建的一个user library,然后把所需要的四个库文件放里面 ...

  8. 面试题-Redis、MongoDB、Memcached[转]

    https://blog.csdn.net/gangsijay888/article/details/81213811 一.缓存 搞懂缓存那些事:https://blog.csdn.net/a7248 ...

  9. Cesium中导入三维模型方法(dae到glft/bgltf) 【转】

    http://blog.csdn.net/l491453302/article/details/46766909 目录(?)[+] Cesium中目前支持gltf和bgltf两种格式.“gltf是kh ...

  10. 【Scala】Scala-case-参考资料

    Scala-case-参考资料 scala case_百度搜索 Scala School - 基础知识(续) scala case匹配值 - CSDN博客 scala入门教程:scala中的match ...