public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpClient httpClient=new DefaultHttpClient();
HttpGet get=new HttpGet("http://open.t.58.com/api/citys");
try {
//发送请求
HttpResponse response= httpClient.execute(get);
//通过HttpReponse对象 获得HttpEntity
HttpEntity entity=response.getEntity();
//通过entity得到返回的输入流
if(response.getStatusLine().getStatusCode()==200){
InputStream is=entity.getContent();
ParseXMLUtil parseXMLUtil=new ParseXMLUtil();
List<City> list= parseXMLUtil.parseXML(is);
}
if(Response.getStatusLine().getStatusCode()==405){
Toast.MakeText(MainActivity.this,"找不到方法",3000).show();
}
if(Response.getStatusLine().getStatusCode()==500){
Toast.MakeText(MainActivity.this,"服务端出现异常",3000).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
public class ParseXMLUtil {
private List<City> list;
private City city;
private String contentValue;
public List<City> parseXML(InputStream is) throws Exception{
//新建工程
SAXParserFactory factory=SAXParserFactory.newInstance();
//得到saxparser类
SAXParser saxParser=factory.newSAXParser();
//得到XMLReader
XMLReader reader=saxParser.getXMLReader();
//设置读取xml的处理类
reader.setContentHandler(new MyHandler());
//开始解析
reader.parse(new InputSource(is));
return list;
}
/**
* @author shenyiya
*
* <? xml version="1.0" charset=utf-8 ?>
* <citys>
* <city>
* <id>1</id>
* <name>亳州</name>
* <enname>bozhou</enname>
* </city>
* <city>
* <id>2</id>
* <name>香港</name>
* <enname>hk</enname>
* </city>
* </citys>
*/
//xml的处理类
class MyHandler extends DefaultHandler{
@Override //文档开始
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
list=new ArrayList<City>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
if("city".equals(qName)){
city=new City();
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
contentValue=new String(ch, start,length);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if("id".equals(qName)){
city.setId(contentValue);
}
if("name".equals(qName)){
city.setName(contentValue);
}
if("enname".equals(qName)){
city.setEnname(contentValue);
}
if("city".equals(qName)){
list.add(city);
}
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
}
}