[英]Spring boot handle request in different controller differentiate by incoming domain
[英]Get geoLocation of incoming request in Spring boot
我想知道我们的 web 应用程序上的用户的位置。 该信息应包含用户的Country
和City
。 我找不到使用Java
或Spring Boot
的好方法。 我曾尝试使用GeoLite2-City
,但它给了我一个例外,说The address 10.212.134.200 is not in the database.
我在我的localhost
上也遇到了这个异常 ip 127.0.0.1
。 以下是我使用的代码:
// String ipAddress = httpServletRequest.getRemoteAddr();
public String getGeoLocation(String ipAddress) {
String geoLocation = "";
try {
File database = ResourceUtils.getFile("classpath:GeoLite2-City/GeoLite2-City.mmdb");;
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
CityResponse response = dbReader.city(InetAddress.getByName(ipAddress));
String countryName = response.getCountry().getName();
String cityName = response.getCity().getName();
String postal = response.getPostal().getCode();
String state = response.getLeastSpecificSubdivision().getName();
geoLocation = "Country: " + countryName + "cityName: " + cityName + "postal: " + postal + "state: " + state;
System.out.println(geoLocation);
} catch(Exception ex) {
logger.error("Exception occured while trying to get GeoLocation of user: " + ex);
}
return geoLocation;
}
但我总是例外。
我只下载并添加了Geolite2-city
文件。 我也没有确认是否需要添加任何其他文件。 我添加的依赖项是:
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.0</version>
</dependency>
10.212.134.200 和 127.0.0.1 是仅在您的网络内部或您的机器内部有意义的地址,而不是在互联网上。 MaxMind 无法知道它们的位置。 (您可以通过向外看 window 来判断您所在的城市。)
如果请求实际上来自互联网,那么来自您的网络外部,它可能是代理的。 如果是这种情况,代理可能添加了X-Forwarded-For
或X-Real-IP
请求 header 或包含原始请求者的外部(“真实”)IP 地址的类似请求。 您会将其输入getGeoLocation
。
基于 IP 的地理位置可能无法为您提供原始结果。 假设用户在 VPN 上,那么您将无法获得用户的原始位置。 基于我可以获取的有限上下文,更好的解决方案是在客户端请求用户的位置许可,然后您可以将其发送到服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.