读取客户端请求IP地址详细信息工具类
一工具介绍
这是一款基于淘宝API实现的读取客户端请求IP地址详细信息工具类
1、导入的Jar包
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- Lombok --><!-- 生成set、get(注意开发工具要支持Lombok,否则一定会报错) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
2、涉及的类
AddressDataEntity --- IP地址信息实体类
AddressEntity --- 中间类
AddressUtils --- 工具类
二、代码详解
1、AddressDataEntity
import lombok.Data;
/**
* <p>
* AddressDataEntity.java
* IP地址信息实体类
* </p>
* @since 2019年5月2日 上午10:06:16
* @author XinLau
* @version 1.0
*/
@Data
public class AddressDataEntity {
/**
* ip
*/
private String ip;
/**
* 国家
*/
private String country;
/**
* 国家代码
*/
private String country_id;
/**
* 区域
*/
private String area;
/**
* 区域代码
*/
private String area_id;
/**
* 地区
*/
private String region;
/**
* 地区代码
*/
private String region_id;
/**
* 城市
*/
private String city;
/**
* 城市代码
*/
private String city_id;
/**
* 县
*/
private String county;
/**
* 县代码
*/
private String county_id;
/**
* 网络运营商
*/
private String isp;
/**
* 网络运营商代码
*/
private String isp_id;
}
2、AddressEntity
import lombok.Data;
/**
* <p>
* AddressEntity.java
* </p>
* @since 2019年5月2日 上午10:06:16
* @author XinLau
* @version 1.0
*/
@Data
public class AddressEntity {
/**
* code
*/
private String code;
/**
* data
*/
private AddressDataEntity data;
}
3、AddressUtils
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSON;
/**
* <p>
* AddressUtils.java
* 根据IP地址获取详细的地域信息
* <p>
* 淘宝API : http://ip.taobao.com/service/getIpInfo.php?ip=218.192.3.42<br>
* 新浪API : http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.192.3.42<br>
* 百度API : https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6006&query=218.192.3.42<br>
* 站长API : http://ip.tool.chinaz.com/ajaxsync.aspx?at=ipbatch&ip=218.192.3.42<br>
* </p>
* </p>
* @since 2019年4月29日 下午5:18:29
* @author XinLau
* @version 1.0
*/
public class AddressUtils {
// 淘宝API
private static final String TAO_BAO_API = "http://ip.taobao.com/service/getIpInfo.php";
// 编码格式
private static final String ENCODING = "utf-8";
/**
* <p>
* getAddresses
* 请求
* </p>
* @param content 请求的参数 格式为:name=xxx&pwd=xxx
* @param encodingString 服务器端请求编码。如GBK,UTF-8等
* @throws UnsupportedEncodingException
* @return String
* @author XinLau
* @since 2019年4月29日下午5:20:54
*/
public String getAddresses(String content, String encodingString) throws UnsupportedEncodingException {
// 从http://whois.pconline.com.cn取得IP所在的省市区信息
String returnStr = getResult(TAO_BAO_API, content, encodingString);
if (returnStr != null) {
// 处理返回的省市区信息
//LoggerUtils.formatDebug(AddressUtils.class, "(1) unicode转换成中文前的returnStr : " + returnStr, "AddressUtils.getAddresses");
returnStr = decodeUnicode(returnStr);
//LoggerUtils.formatDebug(AddressUtils.class, "(2) unicode转换成中文后的returnStr : " + returnStr, "AddressUtils.decodeUnicode");
String[] temp = returnStr.split(",");
if(temp.length<3){
return "0";//无效IP,局域网测试
}
return returnStr;
}
return null;
}
/**
* <p>
* getResult
* 请求第三方接口获取IP地址信息
* </p>
* @param urlStr 请求的地址
* @param content 请求的参数 格式为:name=xxx&pwd=xxx
* @param encoding 服务器端请求编码。如GBK,UTF-8等
* @return String
* @author XinLau
* @since 2019年4月29日下午5:23:38
*/
private static String getResult(String urlStr, String content, String encoding) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();// 新建连接实例
connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒
connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒
connection.setDoOutput(true);// 是否打开输出流 true|false
connection.setDoInput(true);// 是否打开输入流true|false
connection.setRequestMethod("POST");// 提交方法POST|GET
connection.setUseCaches(false);// 是否缓存true|false
connection.connect();// 打开连接端口
DataOutputStream out = new DataOutputStream(connection.getOutputStream());// 打开输出流往对端服务器写数据
out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
out.flush();// 刷新
out.close();// 关闭输出流
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据 ,以BufferedReader流来读取
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();// 关闭连接
}
}
return null;
}
/**
* <p>
* decodeUnicode
* unicode 转换成 中文
* </p>
* @param theString
* @return String
* @author XinLau
* @since 2019年4月29日下午5:24:23
*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
aChar = '\t';
} else if (aChar == 'r') {
aChar = '\r';
} else if (aChar == 'n') {
aChar = '\n';
} else if (aChar == 'f') {
aChar = '\f';
}
outBuffer.append(aChar);
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
/**
* <p>
* getIpInfoJson
* 根据IP获取相关信息的json字符串
* </p>
* @param ip
* @return String
* @author XinLau
* @since 2019年5月2日上午8:37:21
*/
public static String getIpInfoJson(String ip) {
AddressUtils addressUtils = new AddressUtils();
String address = "";
try {
address = addressUtils.getAddresses("ip="+ip, ENCODING);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return address;
}
/**
* <p>
* Json2Entity
* IP获取相关信息的json字符串转成实体类
* </p>
* @param json
* @return AddressEntity
* @author XinLau
* @since 2019年5月2日上午10:21:58
*/
public AddressEntity Json2Entity(String json){
AddressEntity addressEntity = JSON.parseObject(json,AddressEntity.class);
return addressEntity;
}
/**
* <p>
* getAddressEntity
* 根据IP获取相关信息的实体对象
* </p>
* @param ip
* @return AddressEntity
* @author XinLau
* @since 2019年5月2日上午10:24:03
*/
public static AddressEntity getAddressEntity(String ip) {
return JSON.parseObject(getIpInfoJson(ip),AddressEntity.class);
}
private static final String[] HEADERS_TO_TRY = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR", "X-Real-IP" };
/**
* <p>
* getClientIpAddress
* 获取客户端ip地址(可以穿透代理)
* </p>
* @param request
* @return String
* @author XinLau
* @since 2019年6月4日下午4:54:01
*/
public static String getClientIpAddress(HttpServletRequest request) {
for (String header : HEADERS_TO_TRY) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
/**
* <p>
* getAddressEntity
* 获取用户IP地址相关信息
* </p>
* @param request
* @return AddressEntity
* @author XinLau
* @since 2019年6月4日下午4:58:43
*/
public static AddressEntity getAddressEntity(HttpServletRequest request) {
return JSON.parseObject(getIpInfoJson(getClientIpAddress(request)),AddressEntity.class);
}
// 测试
public static void main(String[] args) {
// 测试ip 219.136.134.157 中国=华南=广东省=广州市=越秀区=电信
//String ip = "112.245.17.84";
String ip = "124.130.131.90";
AddressEntity json = AddressUtils.getAddressEntity(ip);
System.out.println(json.toString());
}
}
三、注意:
如果不支持lombok插件,请手动生成set、get