Android开发之从网络URL上下载JSON数据

网络下载拉取数据中,json数据是一种格式化的xml数据,非常轻量方便,效率高,体验好等优点,下面就android中如何从给定的url下载json数据给予解析:

主要使用http请求方法,并用到HttpGet和HttpResponse等对象来获取数据。直接上实例代码吧:、

(1)从网络URL上读取json字符串的实现

public String readJSONFeed(String url){

        StringBuilder stringBuilder = new StringBuilder();

        HttpClient client = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(url);

        HttpResponse response;

        try {

            response = client.execute(httpGet);

            StatusLine statusLine = response.getStatusLine();

            int statusCode = statusLine.getStatusCode();

            if(statusCode == 200){

                HttpEntity entity = response.getEntity();

                InputStream content = entity.getContent();

                BufferedReader reader = new BufferedReader(

                        new InputStreamReader(content));

                String line ;

                while((line = reader.readLine())!=null){

                    stringBuilder.append(line);

                }

            }else{

                Log.e("JSON", "Failed to download file");

            }

        } catch (ClientProtocolException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return stringBuilder.toString();

    }

(2)异步方法拉取网络上的数据的实现:

private class ReadJSONFeedTask extends AsyncTask<String, Void, String>{



        StringBuilder stringBuilder  = new StringBuilder();

        @Override

        protected String doInBackground(String... urls) {

            // TODO Auto-generated method stub

            return readJSONFeed(urls[0]);

        }



        @Override

        protected void onPostExecute(String result) {

            // TODO Auto-generated method stub

            String strItem;

            try {

                JSONArray jsonArray = new JSONArray(result);

                for(int i = 0;i<jsonArray.length();i++){

                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    strItem= jsonObject.getString("appeId")+

                            " - "+jsonObject.getString("inputTime") +"\n";

                    stringBuilder.append(strItem);

                }

                ((TextView)findViewById(R.id.tvJson)).setText(stringBuilder.toString());

            } catch (JSONException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            

        }

        

    }

(3)最后如何启一个异步下载任务呢?其实就是new一个上面的异步类对象并执行即可

new ReadJSONFeedTask().execute(jsonUrl);

到此为止,从网络URL上下载json数据已经成功完成了。最后下载后的数据显示结果如下:

Android开发之从网络URL上下载JSON数据

你可能感兴趣的:(Android开发)