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

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

  

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

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

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

HttpRequestUtils.java

package com.seezoon.framework.common.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StopWatch; import com.alibaba.fastjson.JSON;
import com.seezoon.framework.common.context.exception.ServiceException; /**
* 对性能和参数要求敏感,需要自行利用 HttpPoolClient 对象自行构造
*
* @author hdf 2018年4月23日
*/
public class HttpRequestUtils { /**
* 日志对象
*/
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); private static String DEFAULT_CHARSET = "UTF-8"; private static HttpPoolClient defaultHttpPoolClient = new HttpPoolClient(); public static <T> T doGet(String url, Map<String, String> params, Class<T> clazz) {
return JSON.parseObject(doGet(url, params), clazz);
} public static <T> T doPost(String url, Map<String, String> params, Class<T> clazz) {
return JSON.parseObject(doPost(url, params), clazz);
} public static <T> T postJson(String url, Map<String, String> params, Class<T> clazz) {
return JSON.parseObject(postJson(url, params), clazz);
} public static String postJson(String url, Map<String, String> params) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(JSON.toJSONString(params), ContentType.APPLICATION_JSON));
return execute(httpPost);
} public static String postXml(String url,String content) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(content, ContentType.create("application/xml", "UTF-8")));
return execute(httpPost);
}
public static String doGet(String url, Map<String, String> params) {
Assert.hasLength(url, "请求地址为空");
try {
URIBuilder builder = new URIBuilder(url);
builder.setParameters(getNameValuePair(params));
HttpGet httpGet = new HttpGet(builder.toString());
String result = execute(httpGet);
return result;
} catch (Exception e) {
throw new ServiceException(e);
}
} public static String doPost(String url, Map<String, String> params) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(getUrlEncodedFormEntity(params));
return execute(httpPost);
} public static String execute(HttpRequestBase request) {
StopWatch watch = new StopWatch();
watch.start();
CloseableHttpResponse response = null;
try {
response = defaultHttpPoolClient.execute(request);
watch.stop();
String requestURI = request.getURI().toString();
logger.debug("http client:{} comleted use {} ms",requestURI,watch.getTotalTimeMillis());
int status = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == status) {// 成功
HttpEntity entity = response.getEntity();
if (null != entity) {
String result = EntityUtils.toString(entity, DEFAULT_CHARSET);
EntityUtils.consume(entity);
return result;
} else {
throw new ServiceException("请求无数据返回");
}
} else {
throw new ServiceException("请求状态异常失败");
}
} catch (Exception e) {
throw new ServiceException(request.getURI().toString() + "请求失败", e);
} finally {
if (null != response) {
try {
response.close();
} catch (IOException e) {
logger.error("CloseableHttpResponse close error", e);
}
}
}
} private static UrlEncodedFormEntity getUrlEncodedFormEntity(Map<String, String> params) {
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(getNameValuePair(params), DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
}
return entity;
} private static List<NameValuePair> getNameValuePair(Map<String, String> params){
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (null != params && !params.isEmpty()) {
for (Entry<String, String> entry : params.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
return list;
} public static void shutDown() {
defaultHttpPoolClient.shutdown();
}
}

ServiceException.java

package com.seezoon.framework.common.context.exception;

/**
* 自定义异常方便后续扩展
*
* @author hdf 2018年4月20日
*/
public class ServiceException extends RuntimeException { public ServiceException() {
super();
// TODO Auto-generated constructor stub
} public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
} public ServiceException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
} public ServiceException(String message) {
super(message);
// TODO Auto-generated constructor stub
} public ServiceException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
} }

调用使用方法如下:

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

更详细的写在了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. Java 单例模式的常见应用场景

    单例模式(Singleton)也叫单态模式,是设计模式中最为简单的一种模式,甚至有些模式大师都不称其为模式,称其为一种实现技巧,因为设计模式讲究对象之间的关系的抽象,而单例模式只有自己一个对象,也因此 ...

  2. SharePoint Online 创建网站集

    前言 本文介绍如何在Office 365中创建SharePoint网站集. 正文 通过登录地址登录到Office 365环境中,我们可以在左上角的按钮中点开,进入管理员,也可以直接在页面中点击管理: ...

  3. 丑女贝蒂第一至四季/全集Ugly Betty迅雷下载

    本季第一至四季 Ugly Betty (2006-2009)看点:<丑女贝蒂>在Betty Suarez的生命始终只有一个目标:加入到时尚行业中去.尽管要变得很聪明,工作很卖力而且要多产, ...

  4. Installing Hyperledger Fabric v1.1 on Ubuntu 16.04 — Part II &  Part III

    This entire tutorial is the second part of the installation of Hyperledger Fabric v1.1. In the previ ...

  5. Chapter 7 -- Functional

    Caveats 说明 As of Java 7, functional programming in Java can only be approximated through awkward and ...

  6. 要恢复页面吗?Chrome未正确关闭

    谷歌chrome浏览器每次打开提示"要恢复页面吗"怎么办? 谷歌chrome浏览器每次打开提示"要恢复页面吗"怎么办? 如下图所示: 每次打开启动谷歌chrom ...

  7. 使用rsync实现客户端与服务器端的文件同步与传送,重点是原理和参数解释

    1.什么是rsync?-rsync是类unix系统下的数据镜像备份工具——remote sync.一款快速增量备份工具 Remote Sync,远程同步 支持本地复制,或者与其他SSH.rsync主机 ...

  8. Spring(AbstractRoutingDataSource)实现动态数据源切换

    转自: http://blog.51cto.com/linhongyu/1615895 一.前言 近期一项目A需实现数据同步到另一项目B数据库中,在不改变B项目的情况下,只好选择项目A中切换数据源,直 ...

  9. C#系列教程——对一个对象的装箱取消转换

    代码如下: [csharp]   using System;   class Unboxing_Test   {       static void Main()        {           ...

  10. 已知(x,y,z,yaw,pitch,roll)如何得到4*4的转换矩阵?

    作者:Nicholas链接:https://www.zhihu.com/question/41514206/answer/104827395来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商 ...