【发布时间】:2016-12-09 00:51:20
【问题描述】:
我有以下代码。它运作良好,但我意识到我从未关闭过InputStream。研究,似乎我应该通过在我的一个捕获后添加 finally 来关闭它。
Q1:我需要关闭InputStream吗?
Q2:如果是,怎么做?
这是我的代码示例:
public void refreshWind (final double lat, final double lon){
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... strings) {
String YQL = String.format("select * from weather.forecast where woeid in (SELECT woeid FROM geo.places WHERE text=\"(%s,%s)\")", lat, lon);
String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));
try {
URL url = new URL(endpoint);
URLConnection connection =url.openConnection();
connection.setReadTimeout(10 *1000);
connection.setConnectTimeout(10 *1000);
InputStream inputStream =connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) !=null){
result.append(line);
}
return result.toString();
}catch (Exception e) {
error = e;
}
return null;
}
@Override
protected void onPostExecute(String s) {
if (s ==null && error !=null){
callback.serviceFailure(error);
return;
}
try {
JSONObject data = new JSONObject(s);
JSONObject queryResults =data.optJSONObject("query");
int count =queryResults.optInt("count");
if (count ==0){
callback.serviceFailure(new LocationWeatherException("Wind information not available at this time."));
return;
}
Channel channel = new Channel();
channel.populate(queryResults.optJSONObject("results").optJSONObject("channel"));
callback.serviceSuccess(channel);
}catch (JSONException e) {
callback.serviceFailure(e);
}
}
}.execute();
}
【问题讨论】:
标签: android android-asynctask inputstream