首页 > 解决方案 > 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();
    }
}   

标签: javajson

解决方案


编码参数值呢?编码addresskey

String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + 
URLEncoder.encode(address, "UTF-8"); + "?key=" + URLEncoder.encode(key, "UTF-8");

URLEncoder 应该是要走的路。您只需要记住仅对单个查询字符串参数名称和/或值进行编码


推荐阅读