我正在尝试检索JSON对象并通过它解析,这样我就可以在地图上的2个点之间获取相应的LatLng对象。到目前为止,我已经实现了一个看起来像这样的测试类:
/**
* Necessary imports
*/
public class DemoDirections extends AsyncTask<String, Void, Void > {
ArrayList<LatLng> latLngs;
JsonFactory JSON_FACTORY = new JsonFactory();
JsonParser jParser;
public DemoDirections() {
//To access the Maps and Directions API for directions
}
protected Void doInBackground(String... src) {
String urlString = "http://maps.googleapis.com/maps/api/directions/json?" +
"origin=" + src[0] +"&destination="+ src[1] +"&sensor=false";
Log.d("URL", urlString);
HttpURLConnection urlConnection = null;
URL url = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
jParser = JSON_FACTORY.createJsonParser(urlConnection.getInputStream());
String test = jParser.nextTextValue() != null ? jParser.nextTextValue() : "its still null" ;
Log.d("test string: ", test);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String... src)
{
}
}
我只想将JSON打印为字符串,以确保在开始解析JSON输入之前我已正确接收到信息,但始终调用jParser.nextTextValue()或jParser.textValue()返回null,这使我认为我没有正确建立Google API服务。我只是想看看我缺少什么来检索JSON输入并解析它,以便我可以设置LatLng对象。
答案 0 :(得分:1)
好像你的网址没有提供api密钥。
示例API要求网址应如下所示:https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY
示例工作代码:
String API_KEY = "YOUR_API_KEY_STRING";
String input = "1600+Amphitheatre+Parkway,+Mountain+View,+CA";
private static boolean getAddressResult(String input, StringBuilder jsonResults) {
try {
URL requestUrl = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + input " + &key=" + API_KEY;
);
HttpURLConnection connection = (HttpURLConnection)requestUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = null;
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return false;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
long elapsedTime = System.currentTimeMillis();
if(elapsedTime-currentTime>=5000) {
return false;
}
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return false;
}
Log.d("Test", buffer.toString());
return buffer.toString();
}
else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
return false
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return false;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return false;
} catch (Expcetion e) {
return false;
}
return false;
}
请确保您必须在清单文件中设置正确的权限(例如INTERNET)。 您还可以确保设备上的互联网实际已连接。
答案 1 :(得分:0)