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));
}
}