Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpServletRequest#getHeader("User-Agent") returns null browser name

I'm using Java 6. I have very less knowledge of JSP and Servlets.

I'm using the following code to get browser name in which my application is running:

String browserName = requestProvider.get().getHeader("User-Agent");

Also I'm using the following code to get IP address of the machine on which my application is running:

String ipAdd = requestProvider.get().getRemoteAddr();

In both the cases requestProvider is a reference variable of type Provider<HttpServletRequest>. And I'm assured that it is never NULL.

Now the problem is some times I get both values (browserName and ipAdd) NULL. I've written sometimes because I don't have a test case.

So my question is, what are the cases in Java, when these values can be NULL?

What care should I take in coding to avoid this issue?

Is there any alternate way to get IP address & browser name every time?

like image 485
RAS Avatar asked Jun 18 '13 11:06

RAS


2 Answers

String browserName = requestProvider.get().getHeader("User-Agent");

null means whoever sent the request didn't include a "User-Agent" header.

String ipAdd = requestProvider.get().getRemoteAddr();

is unlikely to return null under normal circumstances, but there are reports the it may do so in edge cases, like after the response has already been sent. Regardless, "get IP address of the machine on which my application is running" doesn't sound like what getRemoteAddr() is for. It's for getting the address of the most recent client or proxy that sent the request.

Is there any alternate way to get IP address & browser name every time?

No. You're entirely dependent on the behavior of the HTTP client and/or any intervening proxies to get information like this.

like image 140
Ryan Stewart Avatar answered Nov 13 '22 22:11

Ryan Stewart


Try using user-agent as lowercase, because it works if we directly access from header.

String browserName = requestProvider.get().getHeader("user-agent");

alternate way to get IP address is

String ip = requestProvider.get().getHeader("True-Client-IP"); this works if we have akamai integeration.

like image 34
Dilip Prakash Avatar answered Nov 13 '22 21:11

Dilip Prakash