用服务器请求数据,解析数据,和使用Handler

来源:互联网 发布:苍老师最经典 知乎 编辑:程序博客网 时间:2024/06/05 20:10

1、先创建Url对象设置相关属性

//先创建Url对象URL url=new URL("http://www.imooc.com/api/teacher?type=3&cid=1");//转换类型HttpURLConnection coon=(HttpURLConnection)url.openConnection();//设置相关方法coon.setRequestMethod("GET");//设置时间coon.setReadTimeout(6000);

2、读取数据并且转为文字

if(coon.getResponseCode()==200){    //保存输入流    InputStream in=coon.getInputStream();    byte[] b=new byte[1024*512];    int len=0;    //保存为缓冲流    ByteArrayOutputStream baos=new ByteArrayOutputStream();    //开始读取数据循环    while((len=in.read(b))>-1){        baos.write(b,0,len);    }    //转为文字    String msg=baos.toString();    Log.e("TAG",msg);
3、json数据解析

//JSON数据解
JSON数据解析
//创建Json对象JSONObject obj=new JSONObject(msg);//get里面的数据int status=obj.getInt("status");String msg2=obj.getString("msg");//测试Log.e("TAG",status+" "+msg2);
4、拿到Data类型的数据

//Date类型数据JSONObject data=obj.getJSONObject("data");String title=data.getString("title");String author=data.getString("author");String content=data.getString("content");Log.e("TAG",title+" "+author+" "+content);
5、利用handler来传数据到主线程

/*通过handler来链接主子线程的数据 将控制权交主线程, */Message message=handler.obtainMessage();Essav e=new Essav(title,author,content);//将数据保存到message.objmessage.obj=e;//覆盖主线程的Messge方法handler.sendMessage(message);
6、使用数据

private TextView title,author,content;    //创建handler    private Handler handler=new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            //将传来的数据重新传给e            Essav e= (Essav) msg.obj;            //使用数据            title.setText(e.getTitle());            author.setText(e.getAuthor());            content.setText(e.getContent());        }    };

0 0