调用Google Places Autocomplete API时遇INVALID_REQUEST(9012)错误求助
排查Google Places Autocomplete API的INVALID_REQUEST(9012)错误
可能的原因及对应解决办法
- SessionToken无效或复用:如果
token未通过AutocompleteSessionToken.newInstance()正确初始化,或者重复使用了已完成请求的token,会触发9012错误。
解决:每次发起搜索请求时创建全新的SessionToken,不要复用之前用过的实例。 - TypesFilter参数格式错误:代码中使用
TypeFilter.ADDRESS.toString()获取类型字符串,可能不符合API要求的格式。
解决:直接传入官方指定的类型字符串数组,比如Arrays.asList("address"),替代枚举值的toString()调用。 - Query参数非法:如果
query为空、null,或者包含特殊字符,会导致请求无效。
解决:请求前校验query,确保不为空,可先调用trim()去除首尾空格,过滤非法字符。 - API密钥配置异常:即使错误码是9012,若API密钥未启用Places API、包名/签名校验不通过或配额超限,也可能引发请求无效。
解决:登录Google Cloud控制台,确认API密钥已启用Places API,且配置了正确的Android应用包名和签名,同时检查配额是否充足。 - 位置参数冲突:若同时调用
setLocationBias和setLocationRestriction,会导致请求参数冲突。
解决:仅保留其中一个位置参数设置,不要同时启用。
修正后的示例代码
// 生成全新的会话Token AutocompleteSessionToken token = AutocompleteSessionToken.newInstance(); // 提前校验查询参数合法性 if (TextUtils.isEmpty(query)) { Log.e(TAG, "查询内容不能为空"); return; } FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder() .setCountries("IN") // 使用API认可的类型字符串 .setTypesFilter(Arrays.asList("address")) .setSessionToken(token) .setQuery(query.trim()) .build(); placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> { for (AutocompletePrediction prediction : response.getAutocompletePredictions()) { Log.i(TAG, prediction.getPlaceId()); Log.i(TAG, prediction.getPrimaryText(null).toString()); } }).addOnFailureListener((exception) -> { if (exception instanceof ApiException) { ApiException apiException = (ApiException) exception; Log.e(TAG, "获取地点失败: " + apiException.getStatusCode() + " - " + apiException.getMessage()); } });
内容的提问来源于stack exchange,提问作者Pranesh Kumar
相关产品推荐
相关产品推荐

