简体   繁体   English

从Google Maps请求JSON给我REQUEST_DENIED

[英]Requesting JSON from Google Maps gives me REQUEST_DENIED

I am wondering why my request keeps getting denied. 我想知道为什么我的请求不断被拒绝。 I'm pretty sure my API key is correct, I selected android in Google Console, gave it my sha1 with my project name and grabbed the API key and stuck it in my project. 我非常确定我的API密钥正确,我在Google控制台中选择了android系统,并为其添加了我的sha1名称和我的项目名称,然后抓取了API密钥并将其粘贴在我的项目中。 However, it still keeps giving me REQUEST_DENIED if I try anything. 但是,如果我尝试任何操作,它仍然会一直给我REQUEST_DENIED。 I'm assuming it's something to do with how I am constructing the URL or if the base URL is broken, or it could be the manner I am requesting the data. 我假设这与我如何构造URL或基本URL是否损坏有关,或者可能是我请求数据的方式。

I'm very new to this and only started playing around a few days ago, so any help would be appreciated. 我对此很陌生,只是几天前才开始玩的,所以任何帮助都将不胜感激。

Here is my code - 这是我的代码-

MainActivity 主要活动

package io.github.invainn.quickeat;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;


public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener, GoogleApiClient.OnConnectionFailedListener {

    Spinner spinner;
    GoogleApiClient mGoogleApiClient;

    private CharSequence mostLikelyPlace;
    private LatLng mostLikelyPlaceLatLng;

    private static final String LOG_TAG = "MainActivity";
    private static final int GOOGLE_API_CLIENT_ID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                .addApi(Places.PLACE_DETECTION_API)
                .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                .build();

        spinner = (Spinner) findViewById(R.id.spinner);

        ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.choices, android.R.layout.simple_spinner_item);
        spinner.setAdapter(adapter);

        setupSearchButton();

        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    Log.i(LOG_TAG, String.format("Place '%s' with " +
                                    "likelihood: %g",
                            placeLikelihood.getPlace().getName(),
                            placeLikelihood.getLikelihood()));
                            if(placeLikelihood.getLikelihood() >= .20) {
                                mostLikelyPlace = placeLikelihood.getPlace().getName();
                                mostLikelyPlaceLatLng = placeLikelihood.getPlace().getLatLng();
                            }
                }
                Toast.makeText(MainActivity.this, "Your current location: " + mostLikelyPlace, Toast.LENGTH_LONG).show();
                likelyPlaces.release();
            }
        });
    }

    private void setupSearchButton() {
        Button searchKeyword = (Button)findViewById(R.id.searchKeyword);

        searchKeyword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Switched to ListActivity", Toast.LENGTH_SHORT).show();

                Bundle args = new Bundle();
                args.putParcelable("currentLocation", mostLikelyPlaceLatLng);

                Intent intent = new Intent(MainActivity.this, List_Activity.class);
                intent.putExtra("bundle", args);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
}

List_Activity List_Activity

package io.github.invainn.quickeat;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;

import org.apache.http.HttpRequestFactory;

import java.net.URL;


public class List_Activity extends ActionBarActivity {
    private static final int PLACE_PICKER_REQUEST = 1;
    private static final String apiAddress = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_);

        // Receive bundle and get currentlocation
        Bundle bundle = getIntent().getParcelableExtra("bundle");
        LatLng currentLocation = bundle.getParcelable("currentLocation");

        new QueryRequest().execute(currentLocation);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_info, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

QueryRequest QueryRequest

package io.github.invainn.quickeat;

import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gms.location.places.Place;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;

import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Created by Anthony on 4/28/2015.
 */
public class QueryRequest extends AsyncTask<LatLng, Integer, String>  {

    private static final String LOG_TAG = "QueryRequest";
    private static final String apiBaseUrl = "https://maps.googleapis.com/maps/api/place";

    private static final String search = "/textsearch";
    private static final String jsonOut = "/json";

    private static final String apiKey = "MYAPIKEY";

    public static ArrayList<Place> search(String keyword, double lat, double lng) {
        ArrayList<Place> resultList = null;

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();

        try {
            StringBuilder sb = new StringBuilder(apiBaseUrl);
            sb.append(search);
            sb.append(jsonOut);
           // sb.append("?sensor=false");
            sb.append("?key=" + apiKey);
            sb.append("&keyword=" + URLEncoder.encode(keyword, "utf8"));
            sb.append("&location=" + String.valueOf(lat) + "," + String.valueOf(lng));
            sb.append("&radius=500");

            //System.out.println(sb.toString());

            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // need to test but im pretty sure this works
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }

            System.out.println(jsonResults);

        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Error processing Places API URL", e);
            return null;
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to Places API", e);
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

    @Override
    protected String doInBackground(LatLng... params) {
        LatLng loc = params[0];
        search("chinese", loc.latitude, loc.longitude );
        return null;
    }
}

If anything else is wrong with my code, please do, I'd like to know. 如果我的代码有其他问题,请这样做,我想知道。

Follow the steps below: 请按照以下步骤操作:

Google Console: Google控制台:

APIs & Auth -> APIs ( Google Places API Web Service ) is enable. API和身份验证 -> API( Google Places API Web服务 )已启用。

APIs & Auth -> Credentials -> create new key -> Browser key (you need to create a browser key and not Android key.). API和 身份 验证 -> 凭据 -> 创建新密钥 -> 浏览器密钥 (您需要创建浏览器密钥而不是Android密钥。)。

For browser key, you not need create a specific key using Sha1. 对于浏览器密钥,您无需使用Sha1创建特定的密钥。

You need to enable the following places api 您需要启用以下Places API

- Google Places API Web Service -Google Places API网络服务

And you are required to use server key for fetching the data of places. 并且您需要使用服务器密钥来获取场所的数据。

To get a server key follow the below steps: APIs & Auth -> Credentials -> create new key -> Server key 要获取服务器密钥,请执行以下步骤: API和身份验证->凭据->创建新密钥->服务器密钥

Browser key will not work. 浏览器密钥不起作用。

I had the same issue and I resolved it by doing the same. 我遇到了相同的问题,并且通过执行相同的操作解决了该问题。

Follow the steps below: 请按照以下步骤操作:

Google Console Api: Google Console Api:

(Google Places API Web Service) is enable. (Google Places API网络服务)已启用。

APIs & Auth -> Credentials -> create new key -> API和身份验证->凭据->创建新密钥->

then select None option in key restriction ...... 然后在密钥限制中选择无选项 ...

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

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