Skip to main content

Detect Client Device and Browser Information in Java

· One min read
Apache Wangye
Software developer and technical writer

A Java web server can inspect HTTP headers such as User-Agent to estimate the browser, operating system, and device category. The result is heuristic, not a trustworthy device identity.

String userAgent = request.getHeader("User-Agent");
String forwardedFor = request.getHeader("X-Forwarded-For");

When the application is behind a trusted reverse proxy, configure the framework to process forwarded headers correctly. Never trust arbitrary X-Forwarded-For values from direct clients.

Prefer a maintained User-Agent parser over an expanding set of regular expressions. User-Agent reduction, browser privacy features, bots, embedded WebViews, and spoofing all limit accuracy.

Use feature detection in the browser when behavior depends on capabilities. Do not use User-Agent parsing for authentication, licensing, fraud decisions, or a stable device identifier. Record only the minimum data needed and consider privacy and retention requirements.

Page views: --

Total views -- · Visitors --