Я пытаюсь получить координаты из местоположения, введенного пользователем с помощью 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();
}
}




А как насчет значений параметров кодирование? кодируют как 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 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
благодарю вас! Понятия не имею, что делает кодировка, обязательно посмотрю!
@ricemvm преобразует строку в формат MIME application/x-www-form-urlencoded. см. stackoverflow.com/help/someone-answers
Код ответа 200 каждый раз? Возможно, содержание ответа было изменено.