Requesting JSON from Google Maps gives me REQUEST_

2019-09-02 21:13发布

问题:

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. However, it still keeps giving me REQUEST_DENIED if I try anything. 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.

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

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

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.

回答1:

Follow the steps below:

Google Console:

APIs & Auth -> APIs (Google Places API Web Service) is enable.

APIs & Auth -> Credentials -> create new key -> Browser key (you need to create a browser key and not Android key.).

For browser key, you not need create a specific key using Sha1.



回答2:

You need to enable the following places api

-Google Places API Web Service

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

Browser key will not work.

I had the same issue and I resolved it by doing the same.



回答3:

Follow the steps below:

Google Console Api:

(Google Places API Web Service) is enable.

APIs & Auth -> Credentials -> create new key ->

then select None option in key restriction......