Android 地方 SDK 受限 API 密钥不起作用

Android Place SDK restricted API key is not working

我知道地点 API 需要服务器密钥才能使用,但我正在为 android 使用地点 SDK。我正在使用受限 Android API 密钥(使用包名称和 SHA1 受限)但它给我以下错误:

This IP, site or mobile application is not authorized to use this API key. Request received from IP address 203.122.438.42, with empty referer

作为参考,我在下面粘贴我的代码:

public PlacesSearchResponse fetch(com.google.maps.model.LatLng location) {
        PlacesSearchResponse request = new PlacesSearchResponse();
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(BuildConfig.MAPS_API_KEY)
                .build();
        try {
            request = PlacesApi.nearbySearchQuery(context, location)
                    .radius(5000)
                    .keyword("Shivam")
                    .type(PlaceType.BAKERY)
                    .await();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return request;
            //Log.d("==", "=====" + request.results[0].name);
        }
    }

我正在使用的依赖项:

> //To get near by locations
> implementation 'com.google.maps:google-maps-services:0.18.0'
> implementation 'com.squareup.okhttp3:okhttp:4.9.0'

您没有为 Android 使用 Places SDK。据我从您的代码中可以看出,您正在为 Google 地图网络服务使用 Java 包装器。 Web 服务始终旨在在服务器端使用,它们接受的唯一限制是对 API 键的 IP 地址限制。

查看 github (https://github.com/googlemaps/google-maps-services-java) 中的 Java 库并注意文档,尤其是“此库的预期用途”部分。它指出

The Java Client for Google Maps Services is designed for use in server applications. This library is not intended for use inside of an Android app, due to the potential for loss of API keys.

If you are building a mobile application, you will need to introduce a proxy server to act as intermediary between your mobile application and the Google Maps API Web Services. The Java Client for Google Maps Services would make an excellent choice as the basis for such a proxy server.

因此,如您所见,Google 解决方案建议引入一个中间代理服务器,您可以在其中将此库与受中间代理服务器 IP 地址限制的 API 密钥一起使用.