Android:解析服务器响应的XML和JSON(包括服务器SSM搭建)

1 篇文章 0 订阅
1 篇文章 0 订阅
安卓APP要实现很多功能(比如登录注册、发表评论等)时都必须要使用到网络数据交互。所以在学习了这部分内容后,就将其以拿一个对象为例整理出来。服务器用的是SSM(SpringMVC、Spring、MyBatis)集合框架,返回响应数据格式为两种xml、json,下面会两种格式都举例
准备环境
  • java IDE:Eclipse(服务器)
  • 数据库:Mysql
  • 构建工具:Maven
  • jdk:1.7以上
  • android IDE:AndroidStudio(客户端)
开发流程如下:
  1. 准备开发环境
  2. 利用SSM搭建服务器
  3. 服务器生成XML或者JSON
  4. 客户端获得链接读取数据
  5. 开始解析 XML:(DOM、SAX、PUll)、Json:(原生态JSONObject,Gson,Fast.json)
  6. 通过listview展示
读取数据流程

我们先搭建服务器

1、新建一个mavenProject :

这里写图片描述

这边我在知道需要哪些依赖架包时,一次性直接添加 (pom.xml):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zking</groupId>
  <artifactId>XmlParser</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>XmlParser Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <!--spring版本-->
    <properties>
        <spring.version>4.3.3.RELEASE</spring.version>
    </properties>

 <dependencies>

        <!-- MyBatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.5</version>
        </dependency>

        <!-- MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>



        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- Log4J -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- 整合Spring,包含SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- 引用c3p0 依赖 start-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.2.1</version>
        </dependency>
        <!-- 引用c3p0 依赖 end-->

        <!-- 引用插件依赖:MyBatis整合Spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!-- JSTL -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


        <!-- JACKSON Start-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.6.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.6.3</version>
        </dependency>

        <!-- JACKSON end-->

  </dependencies>
  <build>
    <finalName>XmlParser</finalName>
  </build>
</project>
2、首先我们先把myBatis搭建成功 注(MyBatisconfig.xml可以省略)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">


  <configuration>
        <!-- 连接数据库信息 -->
    <!--  <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
          <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/test"/>
            <property name="username" value="root"/>
            <property name="password" value="tiger"/>
          </dataSource>
        </environment>
      </environments>  -->    
      <!-- 关联映射文件 -->
     <!-- <mappers>
          <mapper resource="com/zking/entity/Person.xml" />
      </mappers>--> 

  </configuration>

person.java实体类

package com.zking.entity;

public class Person {


    private int pid;
    private String pname;
    private int page;
    public int getPid() {
        return pid;
    }
    public void setPid(int pid) {
        this.pid = pid;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }


    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
    public Person(int pid, String pname, int page) {
        super();
        this.pid = pid;
        this.pname = pname;
        this.page = page;
    }
    public Person(String pname, int page) {
        super();
        this.pname = pname;
        this.page = page;
    }
    @Override
    public String toString() {
        return "Person [pid=" + pid + ", pname=" + pname + ", page=" + page + "]";
    }

}

PersonDao接口:

package com.zking.dao;

import java.util.List;
import java.util.ArrayList;

import com.zking.entity.Person;

public interface PersonDao {

    public void addPerson(Person person);

    public List<Person> getPersons();
}

person映射xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <mapper namespace="com.zking.dao.PersonDao">
      <insert id="addPerson" parameterType="com.zking.entity.Person" >
          insert into person values(null,#{pname},#{page}); 
      </insert>
      <select id="getPersons" resultType="com.zking.entity.Person">
          select * from person
      </select>
  </mapper>
mybatis这边就可以先测试一下搭建成功没有,可以通过

SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(“MyBatisConfig.xml”));拿到Session工厂,具体代码就不贴了


添加一个日志管理
log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3、下面搭建spring框架:

这边先来一个数据连接的配置文件:

uname=root##用户名
upass=tiger##密码
driver_class=com.mysql.jdbc.Driver##mysql驱动类
url=jdbc:mysql://localhost:3306/test//连接url

initPoolSize=5//数据连接池初始最小5个
maxPoolSize=10//数据连接池最大10

applicationContext.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

    <!-- 1.加载properties文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--2.引用数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="user" value="${uname}"></property>
        <property name="password" value="${upass}"></property>
        <property name="jdbcUrl" value="${url}"></property>
        <property name="driverClass" value="${driver_class}"></property>

        <property name="initialPoolSize" value="${initPoolSize}"></property>
        <property name="maxPoolSize" value="${maxPoolSize}"></property>
    </bean>

    <!-- 03.配置SQLSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 3.1引用数据源 -->
        <property name="dataSource" ref="dataSource" ></property>
        <!-- 3.2加载MyBatis配置文件 -->
        <property name="configLocation" value="classpath:MyBatisConfig.xml"></property>
        <!-- 3.3关联Mybatis映射文件 -->
        <property name="mapperLocations" value="classpath:com/zking/entity/*.xml"></property>
    </bean>


    <!-- 配置所有的Dao所在的包 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zking.dao"></property>
    </bean>
</beans>
4、下面搭建SpringMVC

springMVC.xml 这里记得把注解驱动放进去,如果不加,则会报406的错

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">


    <!-- 配置扫描器 -->
    <context:component-scan base-package="com.zking"></context:component-scan>


    <!-- 注解驱动 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>    
</beans>

PersonContorller.java:

package com.zking.contorller;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zking.dao.PersonDao;
import com.zking.entity.Person;
import com.zking.entity.Teacher;

//声明为控制器类
@Controller
public class PersonContorller  {

    //拿到接口对象
    @Autowired
    PersonDao personDao;


    //XML
    @RequestMapping("/getPersons")
    public ModelAndView getPersons(){
        List<Person> mypersons= personDao.getPersons();
        ModelAndView andView=new ModelAndView();
        andView.addObject("mypersons",mypersons);
        andView.setViewName("success");
        return andView;
    }


    //Json格式
    @RequestMapping("/getPersonJson")
    @ResponseBody
    public Teacher getPersonsJson(){
       Teacher teacher= new Teacher();
       teacher.setSchool("天王盖地虎");
       teacher.setNumber(20);
       List<Person> mypersons= personDao.getPersons();
       teacher.setPersons(mypersons);
        return teacher;
    }   
}

5、访问数据

如果是XML格式的,我们需要生成xml文件:
success.jsp:

<%@ page language="java" contentType="text/xml; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@page isELIgnored="false" %>
<persons>
        <c:forEach items="${mypersons}" var="hh">
          <person id="${hh.pid }" name="${hh.pname }">
            <age>${hh.page }</age>
          </person>
        </c:forEach>
</persons>

如果是Json格式的,就只需在Contorller方法上面加上注解@ResponseBody,返回你需要的对象就行了

最后在来一个页面测试一下数据访问

getperson.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
        <a href="getPersons.action">获取xml数据</a>
        <a href="getPersonJson.action">获取Json数据</a>

</body>
</html>

最后web.xml配置如下:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>



    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>



  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

6、到这里,服务器的框架搭完,我们只需要在客户端(应用程序)中去拿数据就可以了

下面在Android app中分为两种方式去拿数据,一种是解析json,一种是解析XML
(6.1)、首先我们先解析json:

package com.example.android30_jsonparser;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.android30_jsonparser.entity.Person;
import com.example.android30_jsonparser.entity.Teacher;
import com.example.android30_jsonparser.uitl.ItemTag;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import static android.os.Build.VERSION_CODES.M;
import static com.alibaba.fastjson.JSON.parseObject;

public class MainActivity extends AppCompatActivity {

    private Teacher teacher;
    private View vHead;//头部
    private ListView lv_json;
    private MyAdpter myAdpter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv_json = (ListView) findViewById(R.id.lv_json);


    }



    public void getJson(View view){
        new MyAsyncTask().execute();
    }

    class MyAdpter extends BaseAdapter{


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

        @Override
        public Object getItem(int i) {
            return teacher.getPersons().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_pid= (TextView) view.findViewById(R.id.tv_item_listview_pid);
                itemTag.tv_pname= (TextView) view.findViewById(R.id.tv_item_listview_pname);
                itemTag.tv_page= (TextView) view.findViewById(R.id.tv_item_listview_page);
                view.setTag(itemTag);
            }
            ItemTag itemTag= (ItemTag) view.getTag();
            itemTag.tv_pid.setText(""+teacher.getPersons().get(i).getPid());
            itemTag.tv_pname.setText(teacher.getPersons().get(i).getPname());
            itemTag.tv_page.setText(""+teacher.getPersons().get(i).getPage());
            return view;
        }
    }



    class MyAsyncTask extends AsyncTask{
        @Override
        protected Object doInBackground(Object[] objects) {//耗时操作
            String path="http://193.168.2.212:8080/XmlParser/getPersonJson.action";
            try {
                //获取路径
                URL url=new URL(path);
                HttpURLConnection  huc= (HttpURLConnection) url.openConnection();
                huc.setRequestMethod("GET");
                huc.setConnectTimeout(5000);
                if(huc.getResponseCode()==200){
                    InputStream is= huc.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    StringBuffer sb=new StringBuffer();
                    String str=null;
                    while ((str=br.readLine())!=null){
                        sb.append(str);
                    }
                    br.close();
                    is.close();
                    //原生态解析(JSONSObject,JSONArray)
//                    JSONObject jb=new JSONObject(sb.toString());
//                    String school=jb.getString("school");
//                    int number=jb.getInt("number");
//                    Log.i("test",school+"   "+number);
//                    JSONArray ja= jb.getJSONArray("persons");
//                    for (int i=0;i<ja.length();i++){
//                       JSONObject jbPerson=  ja.getJSONObject(i);
//                        int pid= jbPerson.getInt("pid");
//                        String pname= jbPerson.getString("pname");
//                        int page= jbPerson.getInt("page");
//                        Log.i("test",pid+"  "+pname+"  "+page);
//                    }

                    //阿里巴巴json解析(导入架包以及引用架包)
                    teacher= JSON.parseObject(sb.toString(), Teacher.class);
//                    Log.i("test","alibaba:"+teacher.getSchool()+"  "+teacher.getNumber());
//                    for (Person person : teacher.getPersons()) {
//                        Log.i("test",""+person);
//                    }

                    //Gson(google自带  需要f4引用架包)
//                    Gson gson=new Gson();
//                    Teacher teacher= gson.fromJson(sb.toString(), Teacher.class);
//                    Log.i("test","google:"+teacher.getSchool()+"  "+teacher.getNumber());
//                        for (Person person : teacher.getPersons()) {
//                        Log.i("test",""+person);
//                    }

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


            return null;
        }


        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            vHead= View.inflate(MainActivity.this, R.layout.item_main, null);
            TextView iv_school= (TextView) vHead.findViewById(R.id.iv_school);
            TextView iv_number= (TextView) vHead.findViewById(R.id.iv_number);
            iv_school.setText(teacher.getSchool());
            iv_number.setText(""+teacher.getNumber());
            //      头布局放入listView中
            lv_json.addHeaderView(vHead);

            myAdpter = new MyAdpter();
            lv_json.setAdapter(myAdpter);
            myAdpter.notifyDataSetChanged();//通知适配器发生改变
        }
    } 
}

(6.2)、布局文件:
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:orientation="vertical"
    tools:context="com.example.android30_jsonparser.MainActivity">

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


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

</LinearLayout>

(6.3)、别忘了在清单文件加网络权限

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

效果图
这里写图片描述


下面是XMl解析方式
package com.example.android29_xmlparser;

import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.android29_xmlparser.entity.Person;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static android.R.attr.x;
import static android.transition.Fade.IN;
import static android.util.Xml.newPullParser;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private List<Person> persons=new ArrayList<>();
    private MyAdapter myAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.lv_xml);
        myAdapter = new MyAdapter();
        listView.setAdapter(myAdapter);

    }

    public void getxml(View view){
        new MyAsyncTask().execute();//执行异步任务
    }


    class  MyAdapter extends BaseAdapter{


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

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

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

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            LinearLayout layout=new LinearLayout(MainActivity.this);
            layout.setOrientation(LinearLayout.HORIZONTAL);
            TextView textViewID=new TextView(MainActivity.this);
            textViewID.setText(""+persons.get(i).getPid());
            TextView textViewName=new TextView(MainActivity.this);
            textViewName.setText(persons.get(i).getPname());
            TextView textViewage=new TextView(MainActivity.this);
            textViewage.setText(""+persons.get(i).getPage());
            layout.addView(textViewID);
            layout.addView(textViewName);
            layout.addView(textViewage);
            return layout;
        }
    }


    class  MyAsyncTask extends AsyncTask{


        private Person person;

        @Override
        protected Object doInBackground(Object[] objects) {
            //确定网络路径
            String path="http://193.168.2.198:8080/XmlParser/getPersons.action";
            try {
                //实例化URL
                URL url=new URL(path);
                //获取连接对象
                HttpURLConnection huc= (HttpURLConnection) url.openConnection();
                // 设置请求方式
                huc.setRequestMethod("GET");
                //设置请求连接超时的时间(优化)
                huc.setConnectTimeout(5000);
                //获取响应状态码
                int code=huc.getResponseCode();
                if(code==200){
                  //获取从服务器返回过来的数据
                    InputStream is=huc.getInputStream();
//                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
//                    String str=null;
//                    while ((str=br.readLine())!=null){
//                        Log.i("test",str);
//                    }
                    //获得pull解析
                    XmlPullParser xpp= Xml.newPullParser();
                    xpp.setInput(is,"utf-8");
                    //得到类型
                    int type=xpp.getEventType();
                    //如果不等于结束文档
                    while(type!=XmlPullParser.END_DOCUMENT){
                        switch (type){
                            case XmlPullParser.START_TAG:
                                //得到标签名
                                String tagName=xpp.getName();
                                if("person".equals(tagName)){
                                    person = new Person();
                                    person.setPid(Integer.parseInt(xpp.getAttributeValue(0)));
                                    person.setPname(xpp.getAttributeValue(1));
                                }
                                if("age".equals(tagName)){
                                    person.setPage(Integer.parseInt(xpp.nextText()));
                                }
                                break;
                            case XmlPullParser.END_TAG:
                                //获取到结束标签的名字
                                String endTagName=xpp.getName();
                                if("person".equals(endTagName)){
                                    persons.add(person);
                                }
                                break;
                        }
                        //重新给type赋值
                        type=xpp.next();
                    }




                }

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

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            myAdapter.notifyDataSetChanged();
        }
    }
}

布局文件:

<?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:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.android29_xmlparser.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_xml"
        ></ListView>


</LinearLayout>

好了,请求以及解析代码上面都写的很详细了,其他的代码只是作一个展示作用。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值