是否可以将时区 API 密钥限制为 Android 应用程序?
通过定义包名称和 SHA-1 哈希,可以将 Google Maps Android API 和 Google Places API 密钥限制为某些 Android 应用程序。
这对 Maps and Places API 来说没有问题,但对 Time Zone API 使用完全相同的设置会不断返回“ REQUEST_DENIED
”。将应用程序限制设置回“无”会导致查询成功,但我不想让我的 API 密钥不受保护。
我调用API的方式如下:
double lat = 51.1789;
double lon = -1.8262;
long time = 1523092938;
String Api_key = "#API_KEY#";
String query = "https://maps.googleapis.com/maps/api/timezone/json?location="+String.format(Locale.ROOT, "%.4f",lat)+","+String.format(Locale.ROOT, "%.4f",lon)+"×tamp="+time+"&key="+ Api_key;
protected JSONObject doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(query);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.connect();
System.out.println(query);
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line);
}
return new JSONObject(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
收到的响应是:
{
"errorMessage" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address XX.XX.XX.XX, with empty referer",
"status" : "REQUEST_DENIED"
}
如果我将应用程序限制设置为无,一切正常:
{
"dstOffset" : 3600,
"rawOffset" : 0,
"status" : "OK",
"timeZoneId" : "Europe/London",
"timeZoneName" : "British Summer Time"
}