IPUtil

package com.mz.base.util;

import java.text.ParseException;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

/**
* IP帮助类
* @author zejun
*/
public class IPUtil {
/**
* IP地址转详细地址
* @param ip
* @param apiName 取值范围:taobao、
* @return
* country 国家
* area 区域,片区
* province 省份
* city 城市
* county 区县
* isp 网络服务商
*/
public static JSONObject ipToLocation(String ip, String apiName){
if(StringUtils.isEmpty(apiName)){
apiName = "taobao";
}
JSONObject json = new JSONObject();

if("taobao".equals(apiName)){
try {
String url = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
String result = UrlUtils.readFromURL(url, "UTF-8", 1024, 10000, null);
JSONObject resultJson = new JSONObject(result);
resultJson = resultJson.getJSONObject("data");

json.put("code", 1);
json.put("country", JSONUtil.getString(resultJson, "country"));
json.put("area", JSONUtil.getString(resultJson, "area"));
json.put("province", JSONUtil.getString(resultJson, "region"));
json.put("city", JSONUtil.getString(resultJson, "city"));
json.put("county", JSONUtil.getString(resultJson, "county"));
json.put("isp", JSONUtil.getString(resultJson, "isp"));
} catch (ParseException e) {
e.printStackTrace();
}
}else if("sina".equals(apiName)){
try {
String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="+ip;
String result = UrlUtils.readFromURL(url, "UTF-8", 1024, 10000, null);
JSONObject resultJson = new JSONObject(result);

json.put("code", 1);
json.put("country", JSONUtil.getString(resultJson, "country"));
json.put("province", JSONUtil.getString(resultJson, "province"));
json.put("city", JSONUtil.getString(resultJson, "city"));
json.put("county", JSONUtil.getString(resultJson, "district"));
json.put("isp", JSONUtil.getString(resultJson, "isp"));
} catch (ParseException e) {
e.printStackTrace();
}
}
return json;
}

public static void main(String[] args) {
/*String url = "http://ip.ws.126.net/ipquery?ip=169.235.24.133";
System.out.println(UrlUtils.readFromURL(url, "GBK", 1024, 10000, null));*/
System.out.println(IPUtil.ipToLocation("169.235.24.133", null));
}

}

转载于:https://www.cnblogs.com/yufeng1102/p/7536290.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值