2015-04-28 69 views
0

我想知道爲什麼我的請求一直被拒絕。 我很確定我的API密鑰是正確的,我在Google Console中選擇了android,給我的sha1添加了我的項目名稱,並獲取了API密鑰並將其粘貼在我的項目中。但是,如果我嘗試任何操作,它仍會一直給我REQUEST_DENIED。我假設這與我構建URL的方式有關,或者基礎URL被破壞,或者它可能是我請求數據的方式。從Google地圖請求JSON會爲我提供REQUEST_DENIED

我很新,只有幾天前纔開始玩,所以任何幫助將不勝感激。

這裏是我的代碼 -

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

如果我的代碼有其他問題,請做,我想知道。

+1

你真的應該隱藏自己的apiKey選擇無選項。 –

+0

只是想到了這一點,謝謝 –

+0

有些問題:你測試你的應用程序已經發布或在虛擬機?您的apikey與您的測試SHA1或您的生產SHA1有關? –

回答

3

按照下面的步驟:

谷歌控制檯:

的API &驗證 - >的API(谷歌Places API的Web服務)是啓用。

的API &驗證 - >憑據 - >創造新的關鍵 - >瀏覽器鍵(你需要創建一個瀏覽器鍵,而不是Android的關鍵)。

對於瀏覽器密鑰,您不需要使用Sha1創建特定的密鑰。

1

您需要啓用以下地方API

- 谷歌Places API的Web服務

你需要使用服務器密鑰對獲取的地方的數據。

要獲得服務器密鑰遵循以下步驟: 的API &驗證 - >憑證 - >創建新的鍵 - >服務器密鑰

瀏覽器鍵將無法正常工作。

我有同樣的問題,我通過這樣做解決了它。

1

按照下面的步驟:

谷歌控制檯API:

(谷歌Places API的Web服務)被啓用。

的API &驗證 - >憑證 - >創建新的鍵 - >

然後在密鑰限制 ......

相關問題