DownloadTask永远不会获取内容并导致应用崩溃

时间:2019-02-16 19:42:41

标签: java android

我正在尝试获取网站内容,但是我的应用程序在调用DownloadTask时仍然崩溃

这是我的DownloadTask和onCreate代码

并且调试也转到Log.i,我的猜测是结果字符串没有得到内容吗?还是downloadtask代码全部错误?

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        URL url;
        HttpURLConnection urlConnection = null;
        String result = "";
        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();
            while  (data !=1) {
                char current = (char) data;
                result += current;
                data = reader.read();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

“ onCreate”

    DownloadTask task = new DownloadTask();
    String result = null;
    try {
        result = task.execute("https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=API_KEY/").get();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Log.i("Contents", result);

1 个答案:

答案 0 :(得分:0)

我知道了

我没有添加返回结果;到代码中,添加它解决了我的问题。

        protected String doInBackground(String... urls) {
        URL url;
        HttpURLConnection urlConnection = null;
        String result = "";
        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();
            while (data != -1) {
                char current = (char) data;
                result += current;
                data = reader.read();
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }