簡體   English   中英

在 Spring 引導中獲取傳入請求的地理位置

[英]Get geoLocation of incoming request in Spring boot

我想知道我們的 web 應用程序上的用戶的位置。 該信息應包含用戶的CountryCity 我找不到使用JavaSpring 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>

筆記:

GeoLite2 是我用來獲取用戶 GeoLocation 的一種方式。 如果您有更好的 API 或建議,請向我建議一種更好的方法來獲取用戶當前的 GeoLocation。

10.212.134.200 和 127.0.0.1 是僅在您的網絡內部或您的機器內部有意義的地址,而不是在互聯網上。 MaxMind 無法知道它們的位置。 (您可以通過向外看 window 來判斷您所在的城市。)

如果請求實際上來自互聯網,那么來自您的網絡外部,它可能是代理的。 如果是這種情況,代理可能添加了X-Forwarded-ForX-Real-IP請求 header 或包含原始請求者的外部(“真實”)IP 地址的類似請求。 您會將其輸入getGeoLocation

基於 IP 的地理位置可能無法為您提供原始結果。 假設用戶在 VPN 上,那么您將無法獲得用戶的原始位置。 基於我可以獲取的有限上下文,更好的解決方案是在客戶端請求用戶的位置許可,然后您可以將其發送到服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM