解析网络xml,并解决乱码问题

1.网络接口

private final static String SEARCH_LOCATION_ADDRESS = "http://www.yodao.com/smartresult-xml/search.s?type=mobile&q=";

 

2.查询

try
				{
					URL url = new URL(SEARCH_LOCATION_ADDRESS + userInput);//包装接口地址
					
					HttpURLConnection httpURLConnection = null;
					
					httpURLConnection = (HttpURLConnection)url.openConnection();
					
					httpURLConnection.setRequestMethod("POST");
					
					httpURLConnection.setDoOutput(true);//上传数据
					
					InputStream inputStream = httpURLConnection.getInputStream();//获取返回的数据流
					
					InputStreamReader isr = new InputStreamReader(inputStream, "gbk");//一定要在这个地方才不会乱码(utf-8,gb2312)
					
					BufferedReader br = new BufferedReader(isr);//利用BufferedReader将流转为String
					
					String result = "";
					
					String temp;
					
					while((temp = br.readLine()) != null)
					{
						result = result + temp;
					}
					
					String location = "";
					location = getStringFromXml(result);//将字符串传递过去,获取位置
					
					Toast toast = Toast.makeText(FindNumberActivity.this, location, Toast.LENGTH_LONG);
					toast.setGravity(Gravity.TOP, 0, 0);
					toast.show();
					
					System.out.println("查询执行完毕!");
					
				}
				catch (MalformedURLException e)
				{
					e.printStackTrace();
				} 
				catch (IOException e) 
				{
					e.printStackTrace();
				} 
			}

 

 

3.从xml中将需要的标签中的内容解析出来

/**
	 * 将xml字符串解析出来,返回地点信息
	 * */
	public String getStringFromXml(String str) 
	{
	
		String result = "";
		
		ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(str.getBytes());
		XmlPullParser parser = Xml.newPullParser();
		try {
			    parser.setInput(tInputStringStream, "UTF-8");
		
	        int eventType = 0;
		    eventType = parser.getEventType();

			while (eventType != XmlPullParser.END_DOCUMENT) 
			{
	
				switch (eventType) 
				{
	
					case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
						
						break;
		
					case XmlPullParser.START_TAG:// 开始元素事件
		
						String name = parser.getName();
		
						if (name.equals("location")) //匹配到location这个标签
						{
							result = parser.nextText().toString();//将标签中的内容读取出来,不是getText()!!!
							
							System.out.println("location解析出来啦:" + result);
							
						}
		
						
						break;
		
					case XmlPullParser.END_TAG:// 结束元素事件
		
						break;
		
				}
		
					eventType = parser.next();
	
			}
			
		}
		 catch (XmlPullParserException e) 
		 {
			 e.printStackTrace();
		 }
		 catch (IOException e) 
		 {
			 e.printStackTrace();
		 }
		return result;//将地址返回
	
	} 
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值