简体   繁体   English

Android上的Google Maps API调用失败,“自动查询”错误

[英]Google Maps API calls failing on Android, “automated queries” error

I'm retrieving addresses from cooridnates using the Google API with the following method: 我正在使用Google API通过以下方法从协调对象中检索地址:

public static String[] getFromLocation(double lat, double lng, int retries) {

    String address = String.format(Locale.getDefault(), 
            "https://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=false&language=" 
                    + Locale.getDefault(), lat, lng);

    String[] res = new String[3];

    String addressLine = "";
    String locality = "";
    String country = "";
    String json = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        URL url = new URL(address);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
        json = jsonResults.toString();
        JSONObject jsonObject = new JSONObject(json);


        if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
            JSONArray results = jsonObject.getJSONArray("results");
            if (results.length() > 0) {
                JSONObject result = results.getJSONObject(0);
                //Address addr = new Address(Locale.getDefault());

                JSONArray components = result.getJSONArray("address_components");
                String streetNumber = "";
                String route = "";
                for (int a = 0; a < components.length(); a++) {
                    JSONObject component = components.getJSONObject(a);
                    JSONArray types = component.getJSONArray("types");
                    for (int j = 0; j < types.length(); j++) {
                        String type = types.getString(j);
                        if (type.equals("locality")) {
                            locality = component.getString("long_name");
                        } else if (type.equals("street_number")) {
                            streetNumber = component.getString("long_name");
                        } else if (type.equals("route")) {
                            route = component.getString("long_name");
                        } else if (type.equals("country")) {
                            country = component.getString("long_name");
                        }
                    }
                }
                addressLine = route + " " + streetNumber;

            }

        }

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception:", e);
        LogsToServer.send(my_id, e);
        if (json != null) LogsToServer.send(my_id, json);
        System.out.println("retries: " + retries);
        if (retries > 0){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            return getFromLocation(lat, lng, retries-1);
        }
    }

    res[0] = addressLine;
    res[1] = locality;
    res[2] = country; 

    return res;
}

The problem is that I very often get the exception: 问题是我经常遇到异常:

03-12 23:54:01.387: E/GetAddressDetails(25248): java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/geocode/json?latlng=48,2&sensor=false&language=en_GB
03-12 23:54:01.387: E/GetAddressDetails(25248):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:197)
03-12 23:54:01.387: E/GetAddressDetails(25248):     at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
03-12 23:54:01.387: E/GetAddressDetails(25248):     at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)

If I launch the method with 4 retries, they may all fail, or sometimes after 2 or 3 I get the address. 如果我通过4次重试启动该方法,它们可能全部失败,或者有时在2或3次后我得到了地址。 Do you know why it fails so often? 您知道为什么它经常失败吗? When I access the same site in my browser I always get the page without errors! 当我在浏览器中访问同一站点时,我总是得到没有错误的页面!

EDIT: I checked the error message returned by Google and it goes like this: 编辑:我检查了由Google返回的错误消息,它像这样:

We're sorry... but your computer or network may be sending automated queries. To protect our users, we can't process your request right now.

Is it a joke? 开玩笑吗 Automated queries? 自动查询? Isn't it the whole purpose of APIs to be called by automatic processes? API的全部目的不是由自动流程调用吗? Also, this happens from many phones and started yesterday. 此外,这是从许多电话开始的,并且从昨天开始。 How does google know that all the requests come from the same app? Google如何知道所有请求都来自同一应用程序?

If you want to get address from cooridnates, you can use Geocoder api. 如果您想从同事那里获取地址,则可以使用Geocoder api。

I used following code in my app to get the city name : 我在应用程序中使用以下代码来get the city name

private double mLongitude; // current longitude
private double mLatitude; // current latitude
private String mCityName; // output cityName

private void getCityName() {
        Geocoder gcd = new Geocoder(this, Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(mLatitude, mLongitude, 1);
            if (addresses.size() != 0) {
                mCityName = addresses.get(0).getAddressLine(1);
                mCityName = mCityName.replaceAll("[\\d.]", "");
                Log.d(TAG + "!!!!!!!!!!!", mCityName);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

If you want get whole address , as I changed a little bit, just do this way: 如果您想获取whole address ,请稍做更改,方法是:

private double mLongitude; // current longitude
private double mLatitude; // current latitude
private String mAddress; // output address

private void getAddress() {
        Geocoder gcd = new Geocoder(this, Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(mLatitude, mLongitude, 1);
            if (addresses.size() != 0) {
                mAddress = addresses.get(0).getAddressLine(0) + " " +
                        addresses.get(0).getAddressLine(1) + " " +
                        addresses.get(0).getAddressLine(2);
                //mAddress = mAddress.replaceAll("[\\d.]", "");
                Log.d(TAG + "!!!!!!!!!!!", mAddress);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM