如何提高AsyncTask中从互联网检索数据的速度?

问题描述 投票:0回答:1

在我的以下代码中,我试图通过传递URL检索一些JSON数据。它工作正常,但是从Internet上获取数据确实需要一些时间。即使数据不那么庞大,但仍然需要花费几秒钟的时间,然后我才能在日志中看到数据。但是我确实想提高从互联网检索数据的速度。

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

    private static final String TAG = "DownloadData";

    @Override
    protected String doInBackground(String... strings) {

        try {
            URL url = new URL(strings[0]);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

            String result = "";

            int data;
            data = inputStreamReader.read();
            while (data != -1) {
                char currentChar = (char) data;
                result += currentChar;
                data = inputStreamReader.read();
            }

            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "Failed";
    }

    @Override
    protected void onPostExecute(String s) {
        Log.d(TAG, "downloaded JSON Data: " + s);
    }
}
android android-asynctask android-json android-internet
1个回答
0
投票

不一一阅读字符。需要太多时间。请改用.readLine()。

不要使用字符串连接,因为这也需要很多时间。而是使用StringBuilder将行添加到。

© www.soinside.com 2019 - 2024. All rights reserved.