13

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?

4

2 回答 2

18

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

null意味着发送请求的人不包含“User-Agent”标头

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

在正常情况下不太可能返回 null,但有报道称它可能会在边缘情况下这样做,例如在响应已经发送之后。无论如何,“获取运行我的应用程序的机器的 IP 地址”听起来不像getRemoteAddr()是为了什么。它用于获取最近发送请求的客户端或代理的地址。

有没有其他方法可以每次都获取 IP 地址和浏览器名称?

不,您完全依赖 HTTP 客户端和/或任何干预代理的行为来获取此类信息。

于 2013-06-19T03:56:05.973 回答
1

尝试使用小写的用户代理,因为如果我们直接从标头访问它就可以工作。

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

获取IP地址的另一种方法是

String ip = requestProvider.get().getHeader("True-Client-IP"); 如果我们有 akamai 整数,这将有效。

于 2014-02-19T09:39:51.697 回答