因此,我的应用程序的一部分构建了一个导航方向字符串,然后尝试解析 JSON 并在地图上绘制折线路线。我首先使用位置变量或区域设置常量构建字符串。我最终得到类似的东西
https://maps.googleapis.com/maps/api/directions/json?origin=Full Frame Documentary Film
Festival, Durham, 27701&destination=601 W Peace St, Raleigh,27605&sensor=false&key={API_KEY}
- 没有新行(我添加它是为了便于阅读),并且 {API_KEY} 是我实际的 api 密钥。
我遇到的问题是,当我将该 URL 字符串传递给此下载 Url(String url String) 方法时
private String downloadUrl(String urlString) throws IOException {
Log.d(TAG, "Downloaded string = " + urlString);
String data = "";
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
// Display our JSON in our browser (to show us how we need to implement our parser)
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(urlString));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
URL url = new URL(urlString);
// Create a http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// read in our data
stream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuffer sb = new StringBuffer();
// read in our data in, and append it as a single data string
String line = "";
while ((line = br.readLine()) != null) {
Log.d(TAG,"url download stream: " + line);
sb.append(line);
}
data = sb.toString();
br.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
Log.d(TAG, "Downloaded data = " + data);
stream.close();
urlConnection.disconnect();
}
return data;
}
JSON 在我的浏览器中正确显示,我看到了 Google 在文档中描述的所有内容。但在接下来的几行中,当我尝试打开 URL 的连接并将 JSON 拉入字符串进行解析时,我收到 System.err 通知
05-02 09:56:01.540: W/System.err(32232): java.io.FileNotFoundException:
https://maps.googleapis.com/maps/api/directions/json?origin=Full Frame Documentary
Film Festival, Durham, 27701&destination=601 W Peace St, Raleigh, 27605&sensor=false&key={API_KEY}
我想我的困惑在于浏览器完美地显示了解析的地址,但随后到(我认为是)同一服务器的连接返回了 FNFE。我的假设是这样吗?如果是这样,我的钥匙可能真的是错的吗?令人困惑的是这段代码在另一个应用程序中工作。