package com.pt.http01; import android.os.Handler; import android.widget.TextView; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by 韬 on 2016-05-14. */ public class XmlThread extends Thread{ private String url; private Handler handler; private TextView tv_result; public XmlThread(String url, Handler handler, TextView tv_result) { this.url = url; this.handler = handler; this.tv_result = tv_result; } @Override public void run() { try { //connect and get the input stream of the XML file URL connurl = new URL(url); HttpURLConnection conn = (HttpURLConnection) connurl.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); InputStream in = conn.getInputStream(); // get Pull parser XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(in,"UTF-8"); //Create a collection to store XML final List<People> peoples = new ArrayList<>(); //get the type of the label int eventType = parser.getEventType(); People people = null; while(eventType != XmlPullParser.END_DOCUMENT){ // get the name of the tag String data = parser.getName(); switch (eventType){ case XmlPullParser.START_TAG: //people start tag creation instance if("people".equals(data)){ people = new People(); } //The attribute name tag sets the attribute to the instance if("name".equals(data)){ people.setName(parser.nextText()); } if("age".equals(data)){ people.setAge(Integer.parseInt(parser.nextText())); } if("school".equals(data)){ people.setSchool(parser.nextText()); } break; case XmlPullParser.END_TAG: / / When the end tag for the people string, add the instance into the collection if("people".equals(data) && people != null){ peoples.add(people); } break; } // Manually call the time processing method eventType = parser.next(); } handler.post(new Runnable() { @Override public void run() { tv_result.setText(peoples.toString()); } }); } catch (MalformedURLException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } catch (XmlPullParserException e) { e.printStackTrace (); } } }