OkHttp解析

public class MainActivity extends AppCompatActivity {

    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
//        new Thread(
//                new Runnable() {
//                    @Override
//                    public void run() {
//                        myHttp();
//                    }
//                }
//
//        ).start();
        asynchronousGet();
    }
    //同步加载
//    public void myHttp() {
//        try {
//            OkHttpClient client=new OkHttpClient();
//            Request request=new Request.Builder()
//                    .url("http://apis.juhe.cn/cook/query?key=c4819a55b9837c8159a054e4cd9b76ec&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF")
//                    .build();
//            Call call = client.newCall(request);
//            Response response = call.execute();
//            if(response.isSuccessful()){
//                String string = response.body().string();
//
//                Gson gson=new Gson();
//                Bean bean = gson.fromJson(string, Bean.class);
//                List<Bean.ResultBean.DataBean> list = bean.getResult().getData();
//                System.out.println("解析得数据"+list);
//                lv.setAdapter(new MyAdapter(MainActivity.this,list));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    //异步加载
    public void asynchronousGet(){

        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url("http://apis.juhe.cn/cook/query?key=c4819a55b9837c8159a054e4cd9b76ec&menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson=new Gson();
                Bean bean = gson.fromJson(string, Bean.class);
                final List<Bean.ResultBean.DataBean> list = bean.getResult().getData();
                System.out.println("解析得数据"+list);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyAdapter adapter=new MyAdapter(MainActivity.this,list);
                        lv.setAdapter(adapter);
                        //adapter.notifyDataSetChanged();
                    }
                });

            }
        });

    }
    }

 

posted on 2017-09-28 13:36  权威的程序  阅读(225)  评论(0编辑  收藏  举报