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", "");
			}
			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", "");
			else
			    Log.i("XXX", "<"+localName+">"+content+"");
		}
	}

xml文件格式:


0
成功



你可能感兴趣的:(Android)