您的位置:首页 > 理论基础 > 计算机网络

读取网络上的json文件

2017-10-13 16:13 211 查看
例:

String path = "http://mnews.gw.com.cn/wap/data/news/news/mobile/jbgg/page_1.json";

这个网络路径对应的是json文件,而不是json字符串

Fragment传过来的分类标识(category)

数据新闻 /xbsjxw

快讯 txs//json格式与其他7个不一样

头条 /toutiao

精编公告 /news/mobile/jbgg

美股 /news/mobile/mgxw

港股 /news/mobile/ggxw

基金 /news/mobile/jjxw

理财 /news/mobile/lcxw

代码如下(展示数据的Fragment):

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Environment;

import android.support.annotation.Nullable;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONArray;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import myapplication.monthexamdemo1.DataDataBean;

import myapplication.monthexamdemo1.R;

import myapplication.monthexamdemo1.XListViewAdapter;

import myapplication.monthexamdemo1.xlistview.XListView;

/**

 * Created by Administrator on 2017/10/13.

 */

public class DataFragment extends Fragment implements XListView.IXListViewListener {

    private XListView xListView;

    private String pathBody = "http://mnews.gw.com.cn/wap/data/news";

    private int page_num;

    private List<DataDataBean.DataBean> list = new ArrayList<>();

    private XListViewAdapter adapter;

    private String category;

    @Nullable

    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.datafragment_item, container, false);

        xListView = view.findViewById(R.id.datafragment_x_list_view);

        xListView.setPullRefreshEnable(true);

        xListView.setPullLoadEnable(true);

        xListView.setXListViewListener(this);

        return view;

    }

    @Override

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        Bundle bundle = getArguments();

        category = bundle.getString("category");

        page_num = 1;

        getDateFromNet(getPath());

    }

    public String getPath(){

        String path = pathBody + category + "/page_" + page_num + ".json";

        return path;

    }

    public void getDateFromNet(final String path){

        new AsyncTask<Void, Void, String>(){

            @Override

            protected String doInBackground(Void... voids) {

                try {

                    URL url = new URL(path);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestMethod("GET");

                    connection.setConnectTimeout(5000);

                    connection.setReadTimeout(5000);

                    int responseCode = connection.getResponseCode();

                    if(responseCode == 200){

                        InputStream inputStream = connection.getInputStream();

                        //根据分类标识为不同的数据在sd卡目录下创建文件夹,用来存储不同类别的json文件

                        File folder = new File(Environment.getExternalStorageDirectory().getPath()+category);

                        if(!folder.exists()){

                            folder.
a07a
mkdirs();

                        }

                        //根据当前展示的页数来创建一个json文件,因为这个接口对应的是一个json文件,所以我的思路是先把它读到内存中,然后再读成字符串解析

                        File file = new File(folder, "/" + page_num + ".json");

                        if(!file.exists()){

                            file.createNewFile();

                            BufferedInputStream input = new BufferedInputStream(inputStream);

                            BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));

                            byte[] bytes = new byte[1024<<2];

                            int len = 0;

                            while((len = input.read(bytes)) != -1){

                                output.write(bytes, 0, len);

                            }

                            input.close();

                            output.flush();

                            output.close();

                        }

                        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

                        StringBuffer buffer = new StringBuffer();

                        String readline = null;

                        while((readline = bufferedReader.readLine()) != null){

                            buffer.append(readline);

                        }

                        bufferedReader.close();

                        return  buffer.toString();

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                }

                return null;

            }

            @Override

            protected void onPostExecute(String s) {

                super.onPostExecute(s);

                try {

                    JSONArray jsonArray = new JSONArray(s);

                    Gson gson = new Gson();

                    DataDataBean dataDataBean = gson.fromJson(jsonArray.getString(0), DataDataBean.class);

                    List<DataDataBean.DataBean> data = dataDataBean.getData();

                    list.clear();

                    list.addAll(data);

                    setAdapter();

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        }.execute();

    }

    private void setAdapter() {

        if(adapter == null){

            adapter = new XListViewAdapter(getActivity(), list);

            xListView.setAdapter(adapter);

        }else{

            adapter.notifyDataSetChanged();

        }

    }

    //并不是只有10页,个人给它的一个限制

    @Override

    public void onRefresh() {

        if(page_num < 10){

            page_num++;

            getDateFromNet(getPath());

        }else{

            Toast.makeText(getActivity(), "到顶了", Toast.LENGTH_SHORT).show();

        }

        xListView.stopRefresh();

        Date date = new Date(System.currentTimeMillis());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");

        xListView.setRefreshTime(simpleDateFormat.format(date));

    }

    @Override

    public void onLoadMore() {

        if(page_num > 1){

            page_num--;

            getDateFromNet(getPath());

        }else{

            Toast.makeText(getActivity(), "到底了", Toast.LENGTH_SHORT).show();

        }

        xListView.stopLoadMore();

    }

}

        
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: