有没有可能将时区API密钥限制为Android应用程序?
谷歌地图Android API和谷歌位置API密钥可以通过定义软件包名称和SHA-1哈希值来限制某些Android应用程序。
这对于Maps和Places API没有问题,但是使用完全相同的设置调用TimeZone 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"
}