android http请求并解析返回的xml

String requestUrl = RequestUrlMng.getHost(context)+"/mservices/user/updateNickname.action?nickname="+nickname;
HttpGet httpRequest = new HttpGet(requestUrl);
try{
	HttpClient httpClient = new DefaultHttpClient();
	HttpResponse httpResponse = httpClient.execute(httpRequest);
	if(httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
	{
	     Log.e("XXX", "can't reach:"+httpResponse.getStatusLine().getStatusCode());
	     return;
	}
	SAXParserFactory factory = SAXParserFactory.newInstance();
	SAXParser parser = factory.newSAXParser();
	XMLContentHandler handler = new XMLContentHandler();
	parser.parse(httpResponse.getEntity().getContent(), handler);
	Toast.makeText(context, handler.getResult().getStatus()+":"+handler.getResult().getMsg(), Toast.LENGTH_LONG).show();
}catch(Exception e){
	Log.e("XXX", e.getMessage());
}

class XMLContentHandler extends DefaultHandler{
		private RequestResult res;
		private static final String STATUS = "status";
		private static final String MSG = "msg";
		private String tmpStr;
		private String content;
		public RequestResult getResult(){
			return res;
		}
		@Override
		public void startDocument() throws SAXException{
			
		}
		@Override
		public void characters(char[] ch,int start,int length)
		                    throws SAXException{

		     content = new String(ch,start,length);


		}
		@Override
		public void startElement(String uri,String localName,String name
				,Attributes attrs) throws SAXException{
			if("result".equals(localName)){
				res = new RequestResult();
				Log.i("XXX", "<result>");
			}
			tmpStr = localName;
		}
		@Override
		public void endElement(String uri,String localName,String name)
		                          throws SAXException{
			if(STATUS.equals(localName))
				res.setStatus(content);
			else if(MSG.equals(localName))
				res.setMsg(content);
			if("result".equals(localName))
				Log.i("XXX", "</result>");
			else
			    Log.i("XXX", "<"+localName+">"+content+"</"+localName+">");
		}
	}

xml文件格式:

<result>
<status>0</status>
<msg>成功</msg>
</result>



阅读更多
个人分类: Android
上一篇android 读xml
下一篇android图片处理(Matrix,ColorMatrix)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭