Android获取服务器端数据(解析XML)

时间:2022-12-02 08:02:41

首先服务器端我们需要生成一个XML。(我就用自己的电脑做服务器啦)
下面上代码,

实体类

public class FQ {
private String name;
private String content;
private String time;
public FQ() {
super();
}
public FQ(String name, String content, String time) {
super();
this.name = name;
this.content = content;
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}

控制层

@RequestMapping("getXML.xhtml")
public String getXml(HttpServletRequest request){
List<FQ> fqs = new ArrayList<FQ>();
for (int i = 1; i <= 100; i++) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
fqs.add(new FQ("DD" + i, "今天心情不错nice"+i, year + "-" + month + "-" + day));
}

request.setAttribute("fqs", fqs);
return "getData";
}

我这里用的是SSH框架搭的,就是简单的把一个对象集合放到request域中,然后在jsp页面使用EL表达式遍历出来,下面是JSP 页面遍历的代码

<?xml version="1.0" encoding="UTF-8" ?><%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><fqs><c:forEach items="${fqs}" var="fq">
<fq name="${fq.name}">
<content>${fq.content}</content>
<time>${fq.time}</time>
</fq>
</c:forEach>
</fqs>

这里注意一点,标签和标签间尽量不要有空格,像上面一样就好啦,接下来连上网运行项目。

Window+r 输入cmd –>ipconfig–>回车
Android获取服务器端数据(解析XML)


Android获取服务器端数据(解析XML)

可以看到ip地址为,192.168.42.253(以自己电脑的为标准)然后浏览器地址栏输入

http://192.168.42.253:8090/front/getXML.xhtml

Android获取服务器端数据(解析XML)

服务器端的XML文件生成好了接下来我们要在安卓端解析这个XML

这里我用的是电脑下的安卓模拟器,打开模拟器的浏览器输入
http://192.168.42.253:8090/front/getXML.xhtml效果如下
Android获取服务器端数据(解析XML)

可以看到模拟器也可以访问到这个地址,一个局域网就搭好了

接下来上安卓端代码,我准备拿到这些数据然后放到listview中
先是布局文件
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.zy_parsexml.MainActivity">


<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取XML"
android:onClick="getXML"
/>


<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lv_main_list"
>


</ListView>
</LinearLayout>

item_listview.xml LIstview的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">


<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/tv_item_listview_name" />


<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/tv_item_listview_content" />


<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/tv_item_listview_time" />

</LinearLayout>

这个类用来优化listview

public class ItemTag {
public TextView tv_name;
public TextView tv_content;
public TextView tv_time;
}

实体类FQ

public class FQ {
private String name;
private String content;
private String time;
public FQ() {
super();
}
public FQ(String name, String content, String time) {
super();
this.name = name;
this.content = content;
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}

MainActivity

public class MainActivity extends AppCompatActivity {

private ProgressDialog progressDialog;
private ListView lv_main_list;
String currentTag=null;

private List<FQ> lists=new ArrayList<>();
private MyAdapter myAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//拿到listView
lv_main_list = (ListView) findViewById(R.id.lv_main_list);

//创建适配器
myAdapter = new MyAdapter();
//给listView设置适配器
lv_main_list.setAdapter(myAdapter);


progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在拼命loading中...");
}

//给ListView准备的适配器,这里是内部类
class MyAdapter extends BaseAdapter{

@Override
public int getCount() {
return lists.size();
}

@Override
public Object getItem(int i) {
return lists.get(i);
}

@Override
public long getItemId(int i) {
return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

if(view==null){
view=LayoutInflater.from(MainActivity.this).inflate(R.layout.item_listview,null);

ItemTag itemTag=new ItemTag();

itemTag.tv_content= (TextView) view.findViewById(R.id.tv_item_listview_content);
itemTag.tv_name= (TextView) view.findViewById(R.id.tv_item_listview_name);
itemTag.tv_time= (TextView) view.findViewById(R.id.tv_item_listview_time);

view.setTag(itemTag);
}

ItemTag itemTag= (ItemTag) view.getTag();
itemTag.tv_name.setText(lists.get(i).getName());
itemTag.tv_content.setText(lists.get(i).getContent());
itemTag.tv_time.setText(lists.get(i).getTime());

return view;
}
}





//点击按钮获取网络数据
public void getXML(View view){
//
new MyTask().execute();


}

//通过继承异步任务类获取网络资源
class MyTask extends AsyncTask{

private FQ fq;
private FQ fq1;

@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}

@Override
protected Object doInBackground(Object[] objects) {

final List<FQ> fqs=new ArrayList<>();

//获取网络数据
//01.定义获取网络的数据的路径
String path="http://192.168.42.253:8090/front/getXML.xhtml";
try {
//02.实例化Url
URL url=new URL(path);
//03.获取连接对象
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
//04.设置请求方式
conn.setRequestMethod("GET");
//05.设置请求连接超时的时间
conn.setConnectTimeout(5000);

//06.获取响应码
int code=conn.getResponseCode();
if(code==200){
//07.获取返回过来的数据(XML)
InputStream is =conn.getInputStream();
//08.测试(删除-注释)
//缓冲字符流
String str=null;
// BufferedReader br=new BufferedReader(new InputStreamReader(is));
// while((str=br.readLine())!=null){
// Log.i("test",str);
// }
//09.解析XML
//方式:DOM SAX PULL
//09.1 使用DOM解析

// try {
// DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
// DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
// Document document=documentBuilder.parse(is);
// //获取跟标签
// Element root=document.getDocumentElement();
// Log.i("test","跟标签:"+root.getTagName());
//
// //Node Element
// NodeList nodeList=root.getElementsByTagName("fq");
// for (int i = 0; i <nodeList.getLength() ; i++) {
// Element element= (Element) nodeList.item(i);
// //获取属性name
// String name=element.getAttribute("name");
//
// //获取子标签<content><time>
// Element elementContent= (Element) element.getElementsByTagName("content").item(0);
// String content=elementContent.getTextContent();
//
// Element elementTime= (Element) element.getElementsByTagName("time").item(0);
// String time=elementTime.getTextContent();
// Log.i("test",name+" "+content+" "+time);
//
// FQ fq=new FQ(name,content,time);
// fqs.add(fq);
// }
// }
// catch (ParserConfigurationException e) {
// e.printStackTrace();
// } catch (SAXException e) {
// e.printStackTrace();
// }

//02.使用SAX解析:特点:边读边解析 基于事件(方法)驱动方式

//<name>张三</name>
// try {
// SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
// SAXParser saxParser=saxParserFactory.newSAXParser();
//
// saxParser.parse(is,new DefaultHandler(){
// @Override
// public void startDocument() throws SAXException {
// super.startDocument();
// }
//
// @Override
// public void endDocument() throws SAXException {
// super.endDocument();
// }
//
// @Override
// public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// super.startElement(uri, localName, qName, attributes);
// currentTag=localName;
// if("fq".equals(localName)){
// //实例化对象
// fq = new FQ();
// String name=attributes.getValue(0);
// fq.setName(name);
// }
//
// }
//
// @Override
// public void endElement(String uri, String localName, String qName) throws SAXException {
// super.endElement(uri, localName, qName);
// //细节:
// currentTag=null;
// if("fq".equals(localName)){
// fqs.add(fq);
// }
// }
//
// @Override
// public void characters(char[] ch, int start, int length) throws SAXException {
// super.characters(ch, start, length);
// if("content".equals(currentTag)){
// String content=new String(ch,start,length);
// fq.setContent(content);
// } else if("time".equals(currentTag)){
// String time=new String(ch,start,length);
// fq.setTime(time);
// }
// }
// });
// } catch (ParserConfigurationException e) {
// e.printStackTrace();
// } catch (SAXException e) {
// e.printStackTrace();
// }

try {
//03.使用PULL解析
XmlPullParser pullParser=Xml.newPullParser();
pullParser.setInput(is,"UTF-8");
int type=pullParser.getEventType();

while(type!=XmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_TAG:
//获取开始标签的名字
String startTagName=pullParser.getName();
if("fq".equals(startTagName)){
fq1 = new FQ();
String name=pullParser.getAttributeValue(0);
fq1.setName(name);
}else if("content".equals(startTagName)){
String content= pullParser.nextText();
fq1.setContent(content);
}else if("time".equals(startTagName)){
String time= pullParser.nextText();
fq1.setTime(time);
}
break;
case XmlPullParser.END_TAG:
//获取结束标签的名字
String endTagName=pullParser.getName();
if("fq".equals(endTagName)){
fqs.add(fq1);
}
break;
}
type=pullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}


}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fqs;
}

//更新UI
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);

List<FQ> fqs= (List<FQ>) o;

lists.addAll(fqs);

myAdapter.notifyDataSetChanged();

progressDialog.cancel();
}
}

}

上面写了解析XML 的3种方式 DOM,SAX,和安卓自带的PULL解析 推荐使用SAX和PULL。

最后不要忘记在清单文件中加上联网的权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

将软件运行到模拟器上看效果图
Android获取服务器端数据(解析XML)
这样就完成了获取服务器的数据,是不是很简单呢.小伙伴们快去试试吧~