Geocode API在HTTP响应中返回null

时间:2018-05-17 13:19:29

标签: java json

我正在尝试从使用HTTP请求到Geocode API的用户输入的位置获取坐标。

我传入方法的地址字符串格式为"%"在空格之间,以便它可以放入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();
    }
}   

1 个答案:

答案 0 :(得分:0)

encoding参数值怎么样?编码addresskey

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

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