使用fastjson获取用户的IP所在地
发布时间:2020-12-16 19:15:08 所属栏目:百科 来源:网络整理
导读:/** * 获取用户IP * 转载使用请注明作者地址:http://blog.csdn.net/zgs_shmily * 创建人:Shmily */public class IpUtil {/** * 获取登录用户的IP地址 * @param request HttpServletRequest * @return 登陆用户IP */public static String getIpAddr(HttpSer
/** * 获取用户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("rn"); } 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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |