android訪問webservice

功能:通過android訪問webservice實現手機號碼歸屬地查詢。

1.編寫業務邏輯

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import cn.kafei.utils.StreamTool;
/**
 * 調用webservice業務類
 */
public class AddressService {
	/**
	 * 獲取手機號歸屬地
	 * 
	 * @param mobile手機號
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	public static String getAddress(String mobile) throws Exception,
			IOException {
		// 讀取SOAP協議
		String soap = readSoap();
		soap = soap.replaceAll("\\$mobile", mobile);// 將$mobile替換爲手機號碼
		// 獲取加載的XML數據字節數組,目的是將XML發送至服務器
		byte[] entity = soap.getBytes();
		String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";// webservice地址
		HttpURLConnection conn = (HttpURLConnection) new URL(path)
				.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		// 設置頭字段
		conn.setRequestProperty("Content-Type",
				"application/soap+xml; charset=utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
		conn.getOutputStream().write(entity);// 將實體數據寫入緩存
		if (conn.getResponseCode() == 200) {
			// 發送XML,並且返回結果爲XML形式,解析XML文件獲得查詢結果
			return parseSOAP(conn.getInputStream());
		}
		return String.valueOf(conn.getResponseCode());
	}

	/**
	 * 解析返回的XML數據
	 * 
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	private static String parseSOAP(InputStream xml) throws Exception {
		// <?xml version="1.0" encoding="utf-8"?>
		// <soap12:Envelope
		// xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		// xmlns:xsd="http://www.w3.org/2001/XMLSchema"
		// xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
		// <soap12:Body>
		// <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">
		// <getMobileCodeInfoResult>string</getMobileCodeInfoResult>
		// </getMobileCodeInfoResponse>
		// </soap12:Body>
		// </soap12:Envelope>
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(xml, "UTF-8");
		int event = pullParser.getEventType();
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_TAG:
				if ("getMobileCodeInfoResult".equals(pullParser.getName())) {
					return pullParser.nextText();
				}
				break;
			}
			event = pullParser.next();
		}
		return null;
	}

	/**
	 * 讀取SOAP協議
	 * 
	 * @return
	 * @throws Exception
	 */
	private static String readSoap() throws Exception {
		InputStream inputStream = AddressService.class.getClassLoader()
				.getResourceAsStream("soap12.xml");
		byte[] data = StreamTool.read(inputStream);
		return new String(data);
	}
}

SOAP協議XML文件,放在src目錄(soap12.xml):

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">
      <mobileCode>$mobile</mobileCode>
      <userID></userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>


讀取流中的數據方法

/**
	 * 讀取流中的數據
	 */
	public static byte[] read(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		byte[] b=new byte[1024];
		int len=0;
		while((len=inputStream.read(b))!=-1){
			outputStream.write(b,0,len);
		}
		inputStream.close();
		return outputStream.toByteArray();
	}
2.在activity中調用:

/**
	 * 查詢手機號歸屬地
	 * 
	 * @param v
	 */
	public void query(View v) {
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);// 控制鍵盤顯示和隱藏
			String mobile = mobileText.getText().toString().trim();// 獲取手機號碼
			try {
				String address = AddressService.getAddress(mobile);// 查詢歸屬地
				textView.setText(address.equals("403")? this.getString(R.string.connError) : address);// 顯示查詢結果
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 強制隱藏鍵盤
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), R.string.error, 1)
						.show();
			}
	}


發佈了50 篇原創文章 · 獲贊 11 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章