前端之家收集整理的这篇文章主要介绍了
使用fastjson获取用户的IP所在地,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/**
* 获取用户IP
* 转载使用请注明作者地址:http://blog.csdn.net/zgs_shmily
* 创建人:Shmily
*/
public class IpUtil {
/**
* 获取登录用户的IP地址
* @param request HttpServletRequest
* @return 登陆用户IP
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip.equals("0:0:0:0:0:0:0:1")) {
ip = "本地";
}
if (ip.split(",").length > 1) {
ip = ip.split(",")[0];
}
return ip;
}
/**
* 通过IP获取客户端地址
* @param ip
* @return 客户端地址
*/
public static String getIpInfo(String ip) {
String info = "";
try {
if(ip.length()>15){
info="IP地址错误";
return info;
}else if(ip.equals("本地")){
info="本地局域网";
return info;
}
//通过淘宝IP地址库进行检测
URL url = new URL("http://ip.taobao.com/service/getIpInfo.PHP?ip=" + ip);
HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
htpcon.setRequestMethod("GET");
htpcon.setDoOutput(true);
htpcon.setDoInput(true);
htpcon.setUseCaches(false);//无缓存
InputStream in = htpcon.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuffer temp = new StringBuffer();
String line ="";
while ((line = bufferedReader.readLine()) != null) {
temp.append(line).append("\r\n");
}
bufferedReader.close();
JSONObject obj = JSON.parSEObject(temp.toString());
//code=0表示获取成功获取json,1表示获取数据失败
if (obj.getIntValue("code") == 0) {
JSONObject data = obj.getJSONObject("data");
info += data.getString("country") + " ";
info += data.getString("region") + " ";
info += data.getString("city") + " ";
info += data.getString("isp");
}else if(obj.getIntValue("code") ==1){
info="未知地址";
return info;
}
} catch (Exception e) {
info="网络异常";
e.printStackTrace();
}
return info;
}
}
原文链接:https://www.f2er.com/json/290114.html