Android平台叫用Web Service:樣本

來源:互聯網
上載者:User

標籤:android平台   web service   webservice   

最近在學習Android,隨著行動裝置的流行,當軟體走上商業化的道路,為了爭奪市場,肯定需要支援Android的,所以開始接觸了Android,不過只瞭解皮毛就好,因為我們要做管理者嘛,懂點Android,管理起來容易些。

 

Android學起來也簡單,封裝的更好了,一個個的控制項,像是又回到了VB的趕腳。

 

下面將通過一個樣本講解如何在Android平台叫用Web Service。我們使用互連網現成的Webservice,供查詢手機號碼歸屬地的Web service,它的WSDL為http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl。

 

1)建立Android工程,引入上面下載的ksoap2-android類庫

在Android平台叫用WebService需要依賴於第三方類庫ksoap2,它是一個SOAP Webservice用戶端開發包,主要用於資源受限制的Java環境如Applets或J2ME應用程式(CLDC/ CDC/MIDP)。

而在Android平台中我們並不會直接使用ksoap2,而是使用ksoap2android。KSoap2 Android 是Android平台上一個高效、輕量級的SOAP開發包

 

2)編寫布局檔案res/layout/main.xml      

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:orientation="vertical"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:paddingTop="5dip"      android:paddingLeft="5dip"      android:paddingRight="5dip"      >      <TextView          android:layout_width="fill_parent"           android:layout_height="wrap_content"           android:text="手機號碼(段):"      />      <EditText android:id="@+id/phone_sec"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:inputType="textPhonetic"          android:singleLine="true"          android:hint="例如:1398547"      />      <Button android:id="@+id/query_btn"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_gravity="right"          android:text="查詢"      />      <TextView android:id="@+id/result_text"          android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:layout_gravity="center_horizontal|center_vertical"      />  </LinearLayout>  


 

3)編寫MainActivity類  

  

/**  * Android平台叫用WebService(手機號碼歸屬地查詢)  *   */  public class MainActivity extends Activity {      private EditText phoneSecEditText;      private TextView resultView;      private Button queryButton;        @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);    // 強制在UI線程中操作           StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()       .detectDiskReads().detectDiskWrites().detectNetwork()        .penaltyLog().build());                   StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()       .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()        .build());         phoneSecEditText = (EditText) findViewById(R.id.phone_sec);          resultView = (TextView) findViewById(R.id.result_text);          queryButton = (Button) findViewById(R.id.query_btn);            queryButton.setOnClickListener(new OnClickListener() {              @Override              public void onClick(View v) {                  // 手機號碼(段)                  String phoneSec = phoneSecEditText.getText().toString().trim();                  // 簡單判斷使用者輸入的手機號碼(段)是否合法                  if ("".equals(phoneSec) || phoneSec.length() < 7) {                      // 給出錯誤提示                      phoneSecEditText.setError("您輸入的手機號碼(段)有誤!");                      phoneSecEditText.requestFocus();                      // 將顯示查詢結果的TextView清空                      resultView.setText("");                      return;                  }                  // 查詢手機號碼(段)資訊                  getRemoteInfo(phoneSec);              }          });      }        /**      * 手機號段歸屬地查詢      *       * @param phoneSec 手機號段      */      public void getRemoteInfo(String phoneSec) {          // 命名空間          String nameSpace = "http://WebXml.com.cn/";          // 調用的方法名稱          String methodName = "getMobileCodeInfo";          // EndPoint          String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";          // SOAP Action          String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";            // 指定WebService的命名空間和調用的方法名          SoapObject rpc = new SoapObject(nameSpace, methodName);            // 設定需調用WebService介面需要傳入的兩個參數mobileCode、userId          rpc.addProperty("mobileCode", phoneSec);          rpc.addProperty("userId", "");            // 產生調用WebService方法的SOAP請求資訊,並指定SOAP的版本          SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);            envelope.bodyOut = rpc;          // 設定是否調用的是dotNet開發的WebService          envelope.dotNet = true;          // 等價於envelope.bodyOut = rpc;          envelope.setOutputSoapObject(rpc);            HttpTransportSE transport = new HttpTransportSE(endPoint);          try {              // 調用WebService              transport.call(soapAction, envelope);          } catch (Exception e) {              e.printStackTrace();          }            // 擷取返回的資料          SoapObject object = (SoapObject) envelope.bodyIn;          // 擷取返回的結果          String result = object.getProperty(0).toString();            // 將WebService返回的結果顯示在TextView中          resultView.setText(result);      }  }  


      注意點1nameSpace、methodName 、EndPoint和SOAP Action 資訊,都可以在WSDL中得到。

      注意點2調用WebService介面方法需要傳入的參數時,參數名稱要和WSDL中描述的一致。(網上有些資料說在需要傳入多個參數時,只要多個參數的順序與WSDL中參數出現的順序一致即可,名稱並不需要和WSDL中的一致,但實際測試發現,大多數情況下並不可行!

 

      注意點3 本例中調用WebService後返回的結果如下所示:

           <?xml version="1.0"encoding="utf-8"?> 

            <string xmlns="http://WebXml.com.cn/">1398547:貴州貴陽貴州移動黔中遊卡</string>

這裡明明返回的是xml格式的內容,為什麼我們不需要通過解析xml來擷取我們需要的內容呢?其實:

            //擷取返回的資料

            SoapObject object = (SoapObject) envelope.bodyIn;

ksoap2能夠將返回的xml轉換成SoapObject對象,然後我們就可以通過操作對象的方式來擷取需要的資料了。

 

     注意點4本例中只返回了一個值,但有些WebService會返回多個值該怎麼擷取?擷取方法與本例完全一樣,只是需要注意的是如果是返回多個值,通過第100代碼object.getProperty(0);得到的可能仍然是一個SoapObject。不斷地調用getProperty()方法;總能得到你想要的全部結果。

 

 

4)在AndroidManifest.xml中配置添加訪問網路的許可權  

<?xml version="1.0" encoding="utf-8"?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"        package="com.liufeng.ws.activity"        android:versionCode="1"        android:versionName="1.0">      <application android:icon="@drawable/icon" android:label="@string/app_name">          <activity android:name=".MainActivity" android:label="@string/app_name">              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>          </activity>      </application>       <uses-sdk android:minSdkVersion="4" />       <!-- 訪問網路的許可權 -->      <uses-permission android:name="android.permission.INTERNET" />   </manifest>  

 

5)運行結果

      


源碼下載

http://download.csdn.net/detail/tcl_6666/7365311

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.