原理:通過HTTP協議發送XML數據並調用webservice(soap)
首先定義string.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="app_name">手機號碼歸屬查詢</string>
- <string name="mobile">手機號</string>
- <string name="button">查詢</string>
- <string name="error">連接失敗</string>
- </resources>
構建一個佈局:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/mobile" />
- <EditText
- android:id="@+id/mobile"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/button" />
- <TextView
- android:id="@+id/result"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
效果圖:
然後編寫activity:
- package cn.csdnmobile;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- import cn.csdn.service.MobileService;
- public class MobileNumberBelongActivity extends Activity implements OnClickListener{
- Button submitBtn ;
- EditText numberEt;
- TextView resultTv;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- findViews();
- }
- private void findViews() {
- numberEt = (EditText) this.findViewById(R.id.mobile);
- submitBtn = (Button) this.findViewById(R.id.button);
- resultTv = (TextView) this.findViewById(R.id.result);
- submitBtn.setOnClickListener(this);
- }
- //監聽,判斷並得到數據
- public void onClick(View v) {
- String PhoneNumber = numberEt.getText().toString().trim();
- if(!"".equals(PhoneNumber)){
- try {
- //把數據傳給MobileService類中的getMobileBelong()方法
- String result = MobileService.getMobileBelong(PhoneNumber);
- //顯示經過上面的方法處理過後的數據
- resultTv.setText(result);
- } catch (Exception e) {
- Log.e("TAG", e.toString());
- Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();
- }
- }
- }
- }
在得到輸入的數據後,要去交給傳給MobileService類中的getMobileBelong()方法處理,然後再把處理好的數據返回
- package cn.csdn.service;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import org.xmlpull.v1.XmlPullParser;
- import android.util.Xml;
- import cn.csdn.utils.StreamTool;
- public class MobileService {
- public static String getMobileBelong(String mobile) throws Exception{
- //類加載器,調用getResourceAsStream()方法作爲輸入流讀取資源
- InputStream inStream = MobileService.class.getClassLoader().getResourceAsStream("mobile_soap.xml");
- //調用建立的工具類,得到數據
- byte[] data = StreamTool.readInputStream(inStream);
- //重新封裝數據
- String xml = new String(data,"UTF-8");
- /**replaceAll()方法:基於規則表達式的替換
- * 其中用到了正則表達式,
- * "\\$mobile" :
- * 正則表達式$爲正則中的特殊符號須轉義,即\$mobile
- * 而\爲字符串中的特殊符號,所以用兩個反斜槓,即"\\{1}quot;
- * */
- String soapEntity = xml.replaceAll("\\$mobile", mobile);
- data = soapEntity.getBytes();
- //定義發送的目的地址
- String path="http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
- //建立連接
- URL url = new URL(path);
- // 轉換 HttpURLConnection是專門爲http的連接而設計的類
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- //post發送,設置允許得到一個輸入流
- conn.setDoOutput(true);
- //延遲
- conn.setConnectTimeout(5000);
- //請求方法
- conn.setRequestMethod("POST");
- //設置請求頭類型
- conn.setRequestProperty("Content-Type", "application/soap+xml;charset=utf-8");
- //設置請求頭長度
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- //發送數據
- OutputStream outStream = conn.getOutputStream();
- outStream.write(data);
- outStream.flush();
- outStream.close();
- //請求成功
- if(conn.getResponseCode() == 200){
- //接收數據
- InputStream responseStream = conn.getInputStream();
- return pareseXml(responseStream);
- }
- return null;
- }
- //xml解析器
- private static String pareseXml(InputStream responseStream) throws Exception {
- XmlPullParser parser = Xml.newPullParser();
- parser.setInput(responseStream, "UTF-8");
- int event = parser.getEventType();
- while(event != XmlPullParser.END_DOCUMENT){
- switch(event){
- case XmlPullParser.START_TAG:
- if("getMobileCodeInfoResult".equals(parser.getName())){
- return parser.nextText();
- }
- break;
- }
- event = parser.next();
- }
- return null;
- }
- }
要調用webservice(soap),所以定義mobile_soap.xml
在MobileService.java 中調用此類轉換的語句:InputStream inStream = MobileService.class.getClassLoader().getResourceAsStream("mobile_soap.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>
在調用mobile_soap.xml 的時候,要把xml格式轉換成字節,所以在這裏要定義一個類
在MobileService.java 中調用此類轉換的語句:byte[] data = StreamTool.readInputStream(inStream);
- package cn.csdn.utils;
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- public class StreamTool {
- /**
- * 從輸入流讀取數據
- * 把數據封裝到ByteArrayOutputStream
- * 爲什麼要封裝:可以把它輕而易舉的做一個字節類型的轉換
- *
- * 然後返回
- * @param inStream
- * @return
- * @throws Exception
- */
- public static byte[] readInputStream(InputStream inStream)
- throws Exception {
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = inStream.read(buffer)) != -1) {
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
可以實現了。。。。