由于您指定问题不是给定地址,而是看似“随机”的行为,这可能属于其他“著名”API 的 documented 行为。
至于其他情况,推荐的策略是Exponential backoff for the Geocoding API,基本意思是一定延迟后重试。
如果上述链接失效或发生变化,我引用这篇文章:
指数退避
在极少数情况下,在满足您的请求时可能会出现问题;您可能会收到 4XX 或 5XX HTTP 响应代码,或者 TCP 连接可能只是在您的客户端和 Google 服务器之间的某处失败。通常值得重新尝试请求,因为当原始请求失败时,后续请求可能会成功。但是,重要的是不要简单地循环重复向 Google 的服务器发出请求。这种循环行为可能会使您的客户端和 Google 之间的网络过载,从而导致多方出现问题。
更好的方法是重试,增加尝试之间的延迟。通常,每次尝试都会使延迟增加一个乘法因子,这种方法称为指数退避。
例如,考虑一个希望向 Google Maps Time Zone API 发出此请求的应用程序:
https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510×tamp=1331161200&key=YOUR_API_KEY
以下 Python 示例展示了如何使用指数退避来发出请求:
import json
import time
import urllib
import urllib2
def timezone(lat, lng, timestamp):
# The maps_key defined below isn't a valid Google Maps API key.
# You need to get your own API key.
# See https://developers.google.com/maps/documentation/timezone/get-api-key
maps_key = 'YOUR_KEY_HERE'
timezone_base_url = 'https://maps.googleapis.com/maps/api/timezone/json'
# This joins the parts of the URL together into one string.
url = timezone_base_url + '?' + urllib.urlencode({
'location': "%s,%s" % (lat, lng),
'timestamp': timestamp,
'key': maps_key,
})
current_delay = 0.1 # Set the initial retry delay to 100ms.
max_delay = 3600 # Set the maximum retry delay to 1 hour.
while True:
try:
# Get the API response.
response = str(urllib2.urlopen(url).read())
except IOError:
pass # Fall through to the retry loop.
else:
# If we didn't get an IOError then parse the result.
result = json.loads(response.replace('\\n', ''))
if result['status'] == 'OK':
return result['timeZoneId']
elif result['status'] != 'UNKNOWN_ERROR':
# Many API errors cannot be fixed by a retry, e.g. INVALID_REQUEST or
# ZERO_RESULTS. There is no point retrying these requests.
raise Exception(result['error_message'])
if current_delay > max_delay:
raise Exception('Too many retry attempts.')
print 'Waiting', current_delay, 'seconds before retrying.'
time.sleep(current_delay)
current_delay *= 2 # Increase the delay each time we retry.
tz = timezone(39.6034810, -119.6822510, 1331161200)
print 'Timezone:', tz
当然这不会解决您提到的“虚假回复”;我怀疑这取决于数据质量并且不会随机发生。