顺序读取三个URL

时间:2019-04-09 16:15:37

标签: java android

我有3个页面的url,其内容具有json结构。我必须在异步任务中从URL中读取页面。

如何依次读取3个网址,以便我可以使用3个json保持其顺序?

private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);    //params[0] = my first url
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            return buffer.toString();

            //read also the second and the third url


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

    @Override
    protected void onPostExecute(String result) {
        // ... do something with the first json
        // ... do something with the second json
        // ... do something with the third json

    }
}

1 个答案:

答案 0 :(得分:0)

只需将将一个URL映射到JSON的逻辑移到方法中,并为传入的每个参数调用它。然后,修改AsyncTask,使其输出List<String>而不是{{1 }}来自String

doInBackground()