【发布时间】:2014-06-19 05:59:31
【问题描述】:
所以我的应用程序的一部分构建了一个导航方向字符串,然后尝试解析 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 字符串传递给这个 downloadUrl(String urlString) 方法时
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 在我的浏览器中正确显示,我看到了谷歌在文档中描述的所有内容。但是在以下几行中,当我尝试打开与 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。假设是这种情况,我错了吗?如果是这样,我的钥匙可能真的错了吗?令人困惑的是,这段代码在另一个应用程序中工作。
【问题讨论】:
-
另一件事:不确定,但您似乎将 HTTP 请求与 UI 逻辑混合在一起。涉及网络流量的 IO-ops 不得在 UI-Thread 上执行。使用
AsyncTask等。 -
@hgoebl 代码有点欺骗性,因为这个方法实际上是从我的 AsyncTask 的 doInBackground() 调用的,并且是一个简单地清理代码的方法。再次感谢
-
好的,那么您已经做到了最好的方法:-),但是您可以稍微改进一下异常处理:在依赖
getInputStream()返回响应之前调用urlConnection.getResponseCode()。对于4xx和5xxHTTP 状态码,调用 getInputStream() 会引发异常,如果您对错误响应的正文感兴趣,则必须调用getErrorStream()。 -
@hgoebl 我感觉你已经做了一些 http 连接:P 非常感谢一切都非常有帮助
标签: android google-maps inputstream httpurlconnection google-directions-api