How to parse data from 2 different URLs by asyncTask method

前端 未结 3 1994
北恋
北恋 2021-01-02 18:03

I have an app that get data from a JSON URL. It works perfectly with one URL, but I need to get data from two JSON URLs at the same time. Like some data from one URL and som

3条回答
  •  耶瑟儿~
    2021-01-02 18:20

    that's how i did it, it's in easy way to do it

    public class GetSetting extends AsyncTask,Void,List> {
    
        String urls[] =  new String[]{"http:// first url",
                                  "http:// second url"};
    
    
        @Override
        protected ArrayList doInBackground(List... lists) {
    
            HttpURLConnection urlConnection;
            InputStream inputStream;
            BufferedReader bufferedReader;
            URL urlIfSup;
            ArrayList result = new ArrayList<>();
            try {
    
                // here to connect and get a different type of data  
    
                for (int i = 0; i < 2; i++){ // this one for connect the url from url array in every loop 
    
                    urlIfSup = new URL(urls[i]);
                    urlConnection = (HttpURLConnection) urlIfSup.openConnection();
                    inputStream = urlConnection.getInputStream();
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
    
                    String data = bufferedReader.readLine();
    
                    while(bufferedReader.readLine() != null){
    
                        data += bufferedReader.readLine();
                    }
                    if (i==0) {
    
                        // do something for the first url
    
                    }else if (i==1){
    
                      // do something for the second url
                       // use jSON if you want 
    
    
                      // then do this at the last url       
                        urlConnection.disconnect();
                        inputStream.close();
                        bufferedReader.close();
                    }
                }
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
            return result;
        }
    }
    

提交回复
热议问题