使用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;
	}
}

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...