最近遇到一个项目问题,需要收集用户的地域信息,以便分析用户地域纬度。网上找了些资料,正好遇到聚合数据API中IP的接口(http://www.juhe.cn/docs/api/id/1)正好符合我的需求,所以记录下来,分享给大家。
通过JSP网页获取用户的IP地址:
1,初始化BaseDAO,以及相关变量的声明
BaseDAO dao =(BaseDAOImpl)WebApplicationContextUtils.getRequiredWebApplicationContext(pageContext.getServletContext()).getBean("dao");
String ip="";//IP地址
double ipvalue = 0;
String fromUrl="";//来路URL
String toUrl="";//受访URL
String address="";//IP归属地
IPLocalAddress ipLocationAddress = new IPLocalAddress();
2,获取IP地址
if(request.getRemoteAddr()!=null){
ip=request.getRemoteAddr();//取得IP地址
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();
}
System.out.println(ip);
//计算IP地址所对应的数值
//String[] tmp =ip.split("\\.");
//ipvalue =Double.parseDouble(tmp[0])*256*256*256+Double.parseDouble(tmp[1])*256*256+Double.parseDouble(tmp[2])*256+Double.parseDouble(tmp[3]);
}
if(request.getParameter("fromUrl")!=null&& request.getParameter("fromUrl").length()>0){
fromUrl=request.getParameter("fromUrl");//取得来路URL
}else{
fromUrl="直接进入";
}
if(request.getParameter("toUrl")!=null &&request.getParameter("toUrl").length()>0){
toUrl=request.getParameter("toUrl");//取得受访URL
}
if(ip.startsWith("192")||ip.startsWith("127")){
address="本地";
}else{
if(ip.equals("0:0:0:0:0:0:0:1%0") == false) {
3,聚合数据通过IP查询地址接口:(聚合数据IP接口地址)http://www.juhe.cn/docs/api/id/1
Map<String,String> params = new LinkedHashMap<String, String>();
params.put("key","4b62068c1fc6758c174bcc21e321cb6f");
params.put("ip", ip);
String url ="http://apis.juhe.cn/ip/ip2addr";
try {
ipLocationAddress = HttpJsonAdapter.getInstance().get( url,
params,
IPLocalAddress.class);
if(ipLocationAddress.getResultcode().equals("200")) {
address = ipLocationAddress.getResult().getArea() +"," + ipLocationAddress.getResult().getLocation();
}else {
address = "juhe data Exception";
}
//}}
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}else {
address ="0:0:0:0:0:0:0:1%0";
}
}
4,保存访问记录至数据库中
Traffic traffic = new Traffic();
traffic.setIp(ip);
traffic.setSourceUrl(fromUrl);
traffic.setTargetUrl(toUrl);
traffic.setArea(address);
traffic.setVisitDate(new java.util.Date());
dao.saveOrUpdate(traffic);