gpt4 book ai didi

java - Google 地理编码返回 ZERO_RESULTS

转载 作者:行者123 更新时间:2023-12-02 00:12:13 26 4
gpt4 key购买 nike

我正在使用谷歌地理编码 API 来获取结果,但它返回“ZERO_RESULTS”。下面是代码

public class GeoCode {

public static void main(String[] args) throws Exception {
GeoCode.geocode("latlng=40.714224,-73.961452");
}
private static final String URL = "http://maps.googleapis.com/maps/api/geocode/json";


public static void geocode(String address) throws Exception {

URL url = new URL(URL + "?" + URLEncoder.encode(address, "UTF-8") + "&sensor=false");
URLConnection conn = url.openConnection();
ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
IOUtils.copy(conn.getInputStream(), output);
output.close();

//JSONObject json = new JSONObject(output.toString());
System.out.println(output.toString());
}
}

当我在浏览器地址栏上手动使用该地址时,它会在浏览器上显示 json 结果。但上面的代码实际上有什么问题,它在 json 中返回“ZERO_RESULTS”?

最佳答案

您不需要使用 URLEncoder 对地址进行编码,只需执行以下操作:

URL url = new URL(URL + "?" + address + "&sensor=false");
URLConnection conn = url.openConnection();
ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
IOUtils.copy(conn.getInputStream(), output);
output.close();
System.out.println(output.toString());

或者也许更好:

   URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?" + address + "&sensor=false");
try {
output = new Scanner(url.openStream()).useDelimiter("\\A").next());
} catch (java.util.NoSuchElementException e) {
//empty result
}

关于java - Google 地理编码返回 ZERO_RESULTS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com