Retrieving JSON from URL on Android

前端 未结 6 1825
无人共我
无人共我 2020-12-03 12:56

My phone APP downloads content perfectly in a text mode. Below is a code to do that. I call Communicator class and exectueHttpGet:

URL_Data = new Communicator(

6条回答
  •  被撕碎了的回忆
    2020-12-03 13:23

    Assume that we have a POJO class called Post

    public List getData(String URL) throws InterruptedException, ExecutionException {
        //This has to be AsyncTask because data streaming from remote web server should be running in background thread instead of main thread. Or otherwise your application will hung while connecting and getting data.
        AsyncTask> getTask = new AsyncTask>(){
            @Override
            protected List doInBackground(String... params) {
                List postList  = new ArrayList();
                String response = "";
                try{
                    //Read stream data from url START
                    java.net.URL url = new java.net.URL(params[0]);
                    HttpURLConnection urlConnection = (HttpURLConnection)
                            url.openConnection();
                    BufferedReader reader = new  BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    String line = "";
                    while((line = reader.readLine()) != null){
                        response += line + "\n";
                    }
                    //Read stream data from url END
    
                    //Parsing json data from reponse data START
                    JSONArray jsonArray = new JSONArray(response);
                    for(int i=0;i

提交回复
热议问题