关闭

android http请求并解析返回的xml

标签: androidstringattributesexceptionxmlclass
4366人阅读 评论(0) 收藏 举报
分类:
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>



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:64085次
    • 积分:768
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:21篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论