我们在Java项目的开发中肯定遇到过获取用户的发送请求的一些信息,比如IP、浏览器和操作系统,下面贴上一个常用的工具类代码:
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;
/**
* 获取请求IP地址、浏览器相关信息
*/
public class IpAndAddrUtil {
/**
* 获取发起请求的IP地址
*/
public static String getIp(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();
}
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();
}
}
pom.xml增加以下jar包
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.20</version>
</dependency>
需要注意的是,如果你本地运行的项目使用localhost访问,获取到的ip地址是:,而如果你使用127.0.0.1访问获取到的ip就是:127.0.0.1,这并不是说代码有问题,而是因为你是在本地,项目和访问者在同一台服务器上,所以出现上面的问题,当你发布到服务器上其实就可以获取真实的ip了。
下图是实际运行效果