从谷歌地图请求JSON给我REQUEST_DENIED [英] Requesting JSON from Google Maps gives me REQUEST_DENIED

查看:1601
本文介绍了从谷歌地图请求JSON给我REQUEST_DENIED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很奇怪,为什么我的要求不断得到拒绝。
我是pretty肯定我的API密钥是正确的,我选的Andr​​oid在谷歌控制台,用我的项目名称送给我的SHA1,抓住API密钥,并在我的项目始终不离不弃。但是,它仍然不断给我REQUEST_DENIED,如果我尝试任何事情。我假设它的东西做的,我如何构造URL,或者如果基本URL被打破,也可能是我请求数据的方式。

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.

我很新的这才开始绕前几天打,所以任何帮助将是AP preciated。

I'm very new to this and only started playing around a few days ago, so any help would be appreciated.

下面是我的code -

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;
    }
}

如果别的毛病我的code,请你,我想知道。

If anything else is wrong with my code, please do, I'd like to know.

推荐答案

请按照下列步骤操作:

谷歌控制台:

API和放大器;验证 - >的API(谷歌Places API的Web服务)为使

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

API和放大器;验证 - > 证书 - > 创建新密钥 - > 浏览器键(你需要创建一个浏览器键,而不是Android的关键)。

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

有关浏览器键,你并不需要创建一个使用SHA1特定的键。

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

这篇关于从谷歌地图请求JSON给我REQUEST_DENIED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆