Android 解析本地服务器的XML文件

刚刚接触Android,这两天学习了一下pull解析本地服务器。

首先要注意的有几点是

1:本地服务器的配置(这里不详细说明),如果输入http://localhost/data.xml能显示那就可以了

2:记得给配置文件xml 添加上权限<uses-permission android:name="android.permission.INTERNET"></uses-permission>

3:如果使用的是真机调试那么,必须要使手机与pc机处在同一个局域网,不然是访问不了的,或者你讲自己的服务器放到外网的服务器上。

4:这里解析的地址要写成 http://10.0.2.2/data.xml,不能写成27.0.0.1或者localhost。

首先看看data.xml文件

<apps>
	<app>
		<id>1</id>
		<name>Helen</name>
		<version>1.0</version>
	</app>
	<app>
		<id>22</id>
		<name>Bob</name>
		<version>2.0</version>
	</app>
</apps>

很简单的一个数据文件。


然后是布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".RequestHttpURLConMainActivity" >

    <Button
        android:id="@+id/BTN_REQ_ID" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send Request"/>
    
    <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <TextView
            android:id="@+id/TEV_ID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        
    </ScrollView>    

</LinearLayout>

下面是java文件

package com.example.requesthttpurlcon;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RequestHttpURLConMainActivity extends Activity implements OnClickListener{
 
	public static final int SHOW_RESPONSE = 0 ;
	private Button btn ;
	private TextView tview ;
	
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response = (String) msg.obj ;
				tview.setText(response) ;
				break;
			default:
				break;
			}
		}
		
	} ;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request_http_urlcon_main);
        
        btn = (Button) findViewById(R.id.BTN_REQ_ID) ;
        tview = (TextView) findViewById(R.id.TEV_ID);
        btn.setOnClickListener(this) ;
        
    }


  

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0.getId() == R.id.BTN_REQ_ID){
			SendRequestWithClinet() ;
			Log.i("a","1") ;
			Toast.makeText(RequestHttpURLConMainActivity.this, "yaaoul", Toast.LENGTH_LONG).show() ;
		}
		
		
	}
	
	private void SendRequestWithClinet(){
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				
				// TODO Auto-generated method stub
				try {
					
					
					
					Log.i("a","2") ;
					HttpClient httpClient = new DefaultHttpClient() ;
					HttpGet httpGet = new HttpGet("http://10.0.2.2:80/data.xml") ;
					HttpResponse httpResponse = httpClient.execute(httpGet) ;
					
					if(httpResponse.getStatusLine().getStatusCode()==200){
						HttpEntity entity = httpResponse.getEntity() ;
						String response = EntityUtils.toString(entity,"utf-8") ;
						paresXml(response) ;
						
						
						/*Message message = new Message() ;
						message.what = SHOW_RESPONSE ;
						message.obj = response.toString() ;
						handler.sendMessage(message) ;*/
						Log.i("aaaaaaa",response) ;
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace() ;
				}
			}
		}).start();		
	}
	
	private void paresXml(String xmlData) {
		// TODO Auto-generated method stub
		//Toast.makeText(GetXmlWithPullMainActivity.this, "22", Toast.LENGTH_LONG).show() ;
		try {
			
			Log.i("a","3") ;
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance() ;
			XmlPullParser xmlPullParser = factory.newPullParser() ;
			xmlPullParser.setInput(new StringReader(xmlData)) ;
			int eventType = xmlPullParser.getEventType() ;
			String id = "" ;
			String name = "" ;
			String version = "" ;
			while(eventType !=XmlPullParser.END_DOCUMENT){
				String nodeName = xmlPullParser.getName() ;
				switch (eventType) {
				case XmlPullParser.START_TAG:{
					if("name".equals(nodeName)){
						name = xmlPullParser.nextText() ;
					}else if("id".equals(nodeName)){
						id = xmlPullParser.nextText() ;
					}else if("version".equals(nodeName)){
						version = xmlPullParser.nextText() ;
					}
					break;
				}
				case XmlPullParser.END_TAG:{
					if("app".equals(nodeName)){
						Log.d("MainActivit","id is" + id) ;
						Log.d("MainActivit","name is" + name) ;
						Log.d("MainActivit","version is" + version) ;
						
					}
					break ;
				}
				default:{
					Log.i("a","meiyou") ;
					break;
				}
				}
				eventType = xmlPullParser.next() ;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace() ;
		}
		
	}
	
	
}

运行成功后,会在LogCat界面打出结果。






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值