Pull解析网络请求文件

来源:互联网 发布:淘宝卖家视频怎么上传 编辑:程序博客网 时间:2024/06/05 22:37
/*** 联网请求数据*/private void getData(int i) {list=new ArrayList<Bean>();try {//得到URL对象,并设置访问地址URL url=new URL(path);//得到HttpURLConnection对象HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//设置连接超时httpURLConnection.setConnectTimeout(5000);//设置请求方式 get/posthttpURLConnection.setRequestMethod("GET");//读取超时httpURLConnection.setReadTimeout(5000);//正式联网httpURLConnection.connect();//获得状态码int code =httpURLConnection.getResponseCode();if(code==200){System.out.println("联网请求成功");//获取包含数据的输入流InputStream inputStream = httpURLConnection.getInputStream();// 得到Xml解析器(pull方式)XmlPullParser pullParser = Xml.newPullParser();// 设置要解析的xml文件到解析器里pullParser.setInput(inputStream, "utf-8");String tagName = null;// 得到读取到的事件类型,就是读取到了什么类型的标签(开始标签,结束标签,文本)int eventType = pullParser.getEventType();// 当文档读取结束,循环结束while (eventType != XmlPullParser.END_DOCUMENT) {switch (eventType) {// "文档开始读取"case XmlPullParser.START_DOCUMENT:System.out.println("文档开始读取");break;// 读取到开始标签case XmlPullParser.START_TAG:// 得到当前开始标签的名字tagName = pullParser.getName();if ("news".equals(tagName)) {bean = new Bean();}break;// 读取到文本case XmlPullParser.TEXT:if ("title".equals(tagName)) {bean.setTitle(pullParser.getText().trim());} else if ("body".equals(tagName)) {bean.setBody(pullParser.getText().trim());}else if("pubDate".equals(tagName)){bean.setPubDate(pullParser.getText().trim());}else if("author".equals(tagName)){bean.setAuthor(pullParser.getText().trim());}break;// 读取到结束标签case XmlPullParser.END_TAG:// 得到结束标签名字tagName = pullParser.getName();System.out.println("文档读取到结束标签" + tagName);if ("news".equals(tagName)) {System.out.println(bean.toString());list.add(bean);bean = null;}tagName = "";break;// 文档结束读取"case XmlPullParser.END_DOCUMENT:System.out.println("文档结束读取");break;}// 到下个节点,并且返回下一个节点的类型eventType = pullParser.next();}Message msg = Message.obtain();msg.what = i;handler.sendMessage(msg);}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (XmlPullParserException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

0 0
原创粉丝点击