java - Geocode API 在 HTTP 响应中返回 null
问题描述
我正在尝试从用户使用对 Geocode API 的 HTTP 请求输入的位置获取坐标。
我传递给方法的地址字符串在空格之间用“%”格式化,以便可以放入 URL。
有时,它会返回一个空值,我不知道为什么。
它有时会起作用,所以我认为 JSON 数组获取行没有问题。
public CheckLocation(String address) {
try {
String key = "insert key";
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "?key=" + key;
// String key = "test/";
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Read JSON response and print
JSONObject myResponse = new JSONObject(response.toString());
double laditude = ((JSONArray)myResponse.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
double longitude = ((JSONArray)myResponse.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
formattedAddress = ((JSONArray)myResponse.get("results")).getJSONObject(0)
.getString("formatted_address");
coordinates = (laditude + "," + longitude);
}
catch (Exception e) {
e.printStackTrace();
}
}
解决方案
编码参数值呢?编码address
和key
:
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" +
URLEncoder.encode(address, "UTF-8"); + "?key=" + URLEncoder.encode(key, "UTF-8");
URLEncoder 应该是要走的路。您只需要记住仅对单个查询字符串参数名称和/或值进行编码
推荐阅读
- azure - Azure IoT Central 中 IoT Edge 模块的可写属性
- python - 如何用其他值 django 模型覆盖默认值
- python - 如何在 python 3 中编译 pygame
- android - 无法在 Windows 10 中安装颤振询问权限并在授予权限时出错
- c# - MailKit MailKit.Net.Smtp.SmtpClient.OnSenderNotAccepted 错误
- azure-devops - 第 47 行,在 schemachange 中引发 ValueError("Invalid root folder: %s" % rootfolder) ValueError: Invalid root folder: /home/vsts/work/1/s/migrations
- javascript - 我写的一个扩展停止工作。有人可以帮我解决吗?
- flutter - Flutter - 在使用 Transform.rotate 旋转容器后,它的子手势检测器 ontap 方法不起作用
- python - 如何检查熊猫中的两列在逻辑上是否相同?
- rust - 在没有发送/同步特征的结构上采用 AtomicPtr