/**
* 联网请求数据
*/
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/post
httpURLConnection.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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Pull解析网络请求文件
最新推荐文章于 2020-09-19 11:15:41 发布