简体   繁体   English

一段时间后取消网址连接

[英]Cancel url connection after a certain period of time

I have an app that contacts Yahoo weather API to get the local wind speed. 我有一个与Yahoo weather API联系的应用程序,以获取本地风速。 It's not critical to get wind speed but is desirable and does improve my app's accuracy. 风速并不关键,但它是可取的,它确实提高了我的应用程序的准确性。 I have a method that first checks for an active internet connection before calling for refreshWeather. 我有一种方法,该方法首先在调用refreshWeather之前先检查互联网是否处于活动状态。 It all works groovy. 一切都很时髦。 However, I want to add code to cancel the request if it gets no data after.. say... 15 seconds. 但是,我想添加代码以取消请求,如果它在15秒后没有数据。 Here's the method. 这是方法。 Any suggestions appreciated. 任何建议表示赞赏。

public void refreshWeather (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();
                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("No wind information found for your location"));
                    return;
                }

                Channel channel = new Channel();
                channel.populate(queryResults.optJSONObject("results").optJSONObject("channel"));
                callback.serviceSuccess(channel);
            } catch (JSONException e) {
                callback.serviceFailure(e);
            }
        }
    }.execute();

}

I figured it out myself. 我自己弄清楚了。 I'm adding the solution in case someone else is searching for the same thing. 我正在添加解决方案,以防其他人正在搜索相同的内容。

    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(15000); //15 seconds
    connection.setReadTimeout(15000); //15 seconds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM