네트워크 xml 를 분석 하고 난 코드 문 제 를 해결 합 니 다.

3284 단어 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;//     
	
	} 
 
 

좋은 웹페이지 즐겨찾기