本内容适合初学Android网络编程、XML解析的童鞋查看,主要内容已添加注释,所以只贴代码即可。
效果图:
①访问网络、解析XML文件工具类: WebServiceUtil.java
package com.lee.webservicedemo2.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.util.Log;
/**
* @author Administrator
*网络上很多使用SOAP协议的方法,这里就使用http
*/
public class WebServiceUtil {
static String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
/**
* 使用HttpURLConnection的get方式访问网络,获取手机号码归属地数据流
* By Lee in 2014年9月3日
* */
public static String getAddressGet(Context context, String mobileNumber)
throws IOException {
//String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
path = path + "?mobileCode=" + URLEncoder.encode(mobileNumber, "utf-8")
+ "&userId=";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
Log.v("Lee", "GET conn = " + conn);
if (conn.getResponseCode() == 200) {
Log.v("Lee", "Connect Successed!");
return parserXML(conn.getInputStream());
} else {
Log.v("Lee",
"Connect failed! + error code: " + conn.getResponseCode());
}
return null;
}
/**
* 使用HttpURLConnection的Post方式访问网络,获取手机号码归属地数据流
* By