调用Google Geolocation API返回404:请求有效但无结果,求排查
问题分析与修复方案
你的核心错误是把POST请求的JSON参数直接拼接在URL末尾,且未显式设置请求方法为POST。Google Geolocation API要求通过POST方法提交JSON请求体,而你当前代码默认使用GET请求,将参数硬塞在URL中的方式完全不符合API规范,这才导致了404错误。
错误点拆解
- 你构造的URL将接口地址、密钥和JSON参数直接拼接,这是GET请求的参数传递逻辑,但Geolocation API不支持用GET提交定位数据,必须使用POST
- 代码中未调用
connection.setRequestMethod("POST"),默认发起GET请求,服务器无法识别这种格式的请求,因此返回404
修复后的Java代码
public void getGeo(Cell cell) // cell: mcc, mnc, lac, cid, type, lat, lon, address { try { String json = formJSON(cell); // URL仅保留接口地址与密钥参数 String urlStr = GEO + KEY; URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 关键:设置请求方法为POST connection.setRequestMethod("POST"); // 设置请求头,告知服务器提交的是JSON格式数据 connection.setRequestProperty("Content-Type", "application/json"); // 允许向服务器写入请求体数据 connection.setDoOutput(true); // 将JSON参数写入请求体 try (OutputStream os = connection.getOutputStream()) { byte[] input = json.getBytes("utf-8"); os.write(input, 0, input.length); } int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { StringBuilder response = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); String result = response.toString(); parseJSON(result); this.address = geocodeLocation(); if (!this.error) { cell.setLat(this.latitude); cell.setLon(this.longitude); cell.setAcc(this.accuracy); cell.setAddress(this.address); } } else { // 处理非200响应,读取错误详情 BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); StringBuilder errorResponse = new StringBuilder(); String line; while ((line = errorReader.readLine()) != null) { errorResponse.append(line); } errorReader.close(); this.error = true; this.errMsg = "HTTP Code: " + code + ", Error: " + errorResponse.toString(); } } catch (Exception e) { this.error = true; this.errMsg = e.toString(); } }
额外说明
- 错误提示中的"请求有效但无结果"具有误导性,实际是你的请求格式完全不符合API要求,服务器无法正确解析才返回404
- 注意
formJSON(cell)生成的JSON需格式正确,比如considerIp的值应为布尔值false而非字符串"false"(你的示例中是字符串,这也是潜在问题)
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

