Android智能手机上的Google Directions API会返回状态代码NOT_FOUND

时间:2015-02-23 08:00:50

标签: java android google-maps google-directory-api

我想使用Google Directions API从我的Android应用中的路线获取JSON信息。但我总是得到" NOT_FOUND"作为状态代码。如果我在浏览器中输入我的请求的相同URL,则可以正常工作。

这里我的代码在AsyncTask中:

    @Override
    protected String doInBackground(final String... params) {
        String startAddress = params[0];
        String finishAddress = params[1];
        departureTime = params[2];
        String travelMode = params[3];


        String result = "";
        String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + startAddress
                + "&destination=" + finishAddress + "&departure_time=" + departureTime + "&mode=" + travelMode + "&sensor=true";
        url = url.trim().replace(' ', '+');

        Log.d(TAG, "URL String: " + url);

        try {
            URL urlObject = new URL(url);
            URLConnection urlConn = urlObject.openConnection();

            BufferedReader in = new BufferedReader( new InputStreamReader(urlConn.getInputStream()));

            String inputLine;
            while ((inputLine = in.readLine()) != null){
                result = result + inputLine;
            }
            in.close();

            return result;
        } catch (Exception e) {
            exception = e.toString();
            Log.e(TAG, "Exception getting route from Google Directions API: " + e.toString());
            Logger.e(context, TAG, "Exception getting route from Google Directions API: " + e.toString());
            return null;
        }
    }

输出如下:

02-23 08:54:01.811  25055-25055/de.bmw.ceprouteguide D/PlanRouteActivity﹕ startAddress: Hanauer Straße 46, München, endAddress: Westendstraße 11, München, travelMode: transit, date: 23-02-2015, time: 08:54
02-23 08:54:01.812  25055-25055/de.bmw.ceprouteguide D/PlanRouteActivity﹕ Millis since epoch:1424678040, date string: 23-02-2015 08:54
02-23 08:54:01.816  25055-25618/de.bmw.ceprouteguide D/PlanRouteActivity﹕ URL String: http://maps.googleapis.com/maps/api/directions/json?origin=Hanauer+Straße+46,+München&destination=Westendstraße+11,+München&departure_time=1424678040&mode=transit&sensor=true
02-23 08:54:02.116  25055-25055/de.bmw.ceprouteguide D/PlanRouteActivity﹕ Route: {   "routes" : [],   "status" : "NOT_FOUND"}
02-23 08:54:02.117  25055-25055/de.bmw.ceprouteguide D/PlanRouteActivity﹕ Google Directions status code: NOT_FOUND

任何人都知道问题在哪里?

1 个答案:

答案 0 :(得分:0)

如果您有API密钥 您必须从https://console.developers.google.com

启用API
  1. Google Maps Direction API
  2. Google Maps Android API
  3. 如果没有创建凭据来访问您的启用API。

    等待10分钟,然后重试。