首页 > 编程语言 > 详细

Java Web应用中获取用户请求相关信息,如:IP地址、操作系统、浏览器等信息

时间:2019-06-04 00:13:49      阅读:562      评论:0      收藏:0      [点我收藏+]

一、引入jar文件:

<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.20</version>
</dependency>

二、创建工具类

package com.study.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
* 获取请求IP地址、浏览器相关信息
*/
public class IpAndAddrUtil {
/**
* 获取发起请求的IP地址
*/
public static String getIp(HttpServletRequest request) {
String ip = null;
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("127.0.0.1")) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip = inet.getHostAddress();
}
}
if ((ip != null) && (ip.length() > 15)) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}

/**
* 获取发起请求的浏览器名称
*/
public static String getBrowserName(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
Browser browser = userAgent.getBrowser();
return browser.getName();
}

/**
* 获取发起请求的浏览器版本号
*/
public static String getBrowserVersion(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
//获取浏览器信息
Browser browser = userAgent.getBrowser();
//获取浏览器版本号
Version version = browser.getVersion(header);
return version.getVersion();
}

/**
* 获取发起请求的操作系统名称
*/
public static String getOsName(HttpServletRequest request) {
String header = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(header);
OperatingSystem operatingSystem = userAgent.getOperatingSystem();
return operatingSystem.getName();
}
}

Java Web应用中获取用户请求相关信息,如:IP地址、操作系统、浏览器等信息

原文:https://www.cnblogs.com/qubo520/p/10970845.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!