简体   繁体   中英

Geocode API is returning null in HTTP response

I am trying to get coordinates from a location entered from the user using HTTP request to Geocode API.

The address string I pass into the method is formatted with "%" in between the spaces so that it can be put into a URL.

Sometimes, it will return a null value and I have no idea why.

It works sometimes so I think there isn't a problem with the JSON array get lines.

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();
    }
}   

What about encoding parameters values? encode both address and key :

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

URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM