ksoap2調用webservice

ve的問題:

1.出現錯誤   FATAL EXCEPTION: main

            java.lang.NullPointerException

解決:刪除AndroidManifest.xmel中的 <uses-sdk android:minSdkVersion="8"android: targetSdkVersion ="17" />,即可;


2.FATAL EXCEPTION: main  java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject

解決:ksoap2包沒有導入好,按照下面說的即可!

——————————————————————————————————————

轉載:http://blog.csdn.net/lyq8479/article/details/6428288    手機號查詢

Android平臺調用Web Service示例
下面將通過一個示例講解如何在Android平臺調用Web Service。
既然要調用Web Service,那就要先有Web Service。我們還是選擇使用上篇文章中介紹的查詢手機號碼歸屬地的Web service,它的WSDL爲http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

1)新建Android工程,引入上面下載的ksoap2-android類庫
Android工程的創建就不多說了,主要想說明的是如何向Android工程中添加第三方jar包。當然,添加第3方jar的方式有多種,我個人比較喜歡用下面這種方式,即先將第三方jar包拷貝到工程某個目錄下,再將其加入到工程的Build Path中
例如,我創建的Android工程名爲WSClient,在工程名上點擊右鍵,新建一個Folder(目錄或文件夾),名爲libs,然後將ksoap2-android類庫拷貝到libs目錄中,如下圖所示:
0_13056494647cT0.gif
接着,在jar包ksoap2-android-assembly-2.4-jar-with-dependencies.jar上點擊右鍵,依次選擇“Build Path”-“Add to Build Path”。再在工程名上點擊右鍵,依次選擇“Build Path”-“Config Build Path...”,將看到如下所示界面:
0_1305649801GH83.gif
選中ksoap2 jar包前面的選項框,點擊OK,則完成了ksoap2 jar包的添加(說明:在Android工程中,添加其它jar包的方法完全一樣,操作一兩遍後,你會發現其實很簡單的)。

2)編寫佈局文件res/layout/main.xml

  1. <?xmlversion="1.0"encoding="utf-8"?>

  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

  3. android:orientation="vertical"

  4. android:layout_width="fill_parent"

  5. android:layout_height="fill_parent"

  6. android:paddingTop="5dip"

  7. android:paddingLeft="5dip"

  8. android:paddingRight="5dip"

  9. >

  10. <TextView

  11. android:layout_width="fill_parent"

  12. android:layout_height="wrap_content"

  13. android:text="手機號碼(段):"

  14. />

  15. <EditTextandroid:id="@+id/phone_sec"

  16. android:layout_width="fill_parent"

  17. android:layout_height="wrap_content"

  18. android:inputType="textPhonetic"

  19. android:singleLine="true"

  20. android:hint="例如:1398547"

  21. />

  22. <Buttonandroid:id="@+id/query_btn"

  23. android:layout_width="wrap_content"

  24. android:layout_height="wrap_content"

  25. android:layout_gravity="right"

  26. android:text="查詢"

  27. />

  28. <TextViewandroid:id="@+id/result_text"

  29. android:layout_width="wrap_content"

  30. android:layout_height="wrap_content"

  31. android:layout_gravity="center_horizontal|center_vertical"

  32. />

  33. </LinearLayout>

3)編寫MainActivity類

  1. packagecom.liufeng.ws.activity;

  2. importorg.ksoap2.SoapEnvelope;

  3. importorg.ksoap2.serialization.SoapObject;

  4. importorg.ksoap2.serialization.SoapSerializationEnvelope;

  5. importorg.ksoap2.transport.HttpTransportSE;

  6. importandroid.app.Activity;

  7. importandroid.os.Bundle;

  8. importandroid.view.View;

  9. importandroid.view.View.OnClickListener;

  10. importandroid.widget.Button;

  11. importandroid.widget.EditText;

  12. importandroid.widget.TextView;

  13. publicclassMainActivityextendsActivity {

  14. privateEditText phoneSecEditText;

  15. privateTextView resultView;

  16. privateButton queryButton;

  17. @Override

  18. publicvoidonCreate(Bundle savedInstanceState) {

  19. super.onCreate(savedInstanceState);

  20. setContentView(R.layout.main);

  21. phoneSecEditText = (EditText) findViewById(R.id.phone_sec);

  22. resultView = (TextView) findViewById(R.id.result_text);

  23. queryButton = (Button) findViewById(R.id.query_btn);

  24. queryButton.setOnClickListener(newOnClickListener() {

  25. @Override

  26. publicvoidonClick(View v) {

  27. // 手機號碼(段)

  28. String phoneSec = phoneSecEditText.getText().toString().trim();

  29. // 簡單判斷用戶輸入的手機號碼(段)是否合法

  30. if("".equals(phoneSec) || phoneSec.length() <7) {

  31. // 給出錯誤提示

  32. phoneSecEditText.setError("您輸入的手機號碼(段)有誤!");

  33. phoneSecEditText.requestFocus();

  34. // 將顯示查詢結果的TextView清空

  35. resultView.setText("");

  36. return;

  37. }

  38. // 查詢手機號碼(段)信息

  39. getRemoteInfo(phoneSec);

  40. }

  41. });

  42. }

  43. publicvoidgetRemoteInfo(String phoneSec) {

  44. // 命名空間

  45. String nameSpace = "http://WebXml.com.cn/";

  46. // 調用的方法名稱

  47. String methodName = "getMobileCodeInfo";

  48. // EndPoint

  49. String endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";

  50. // SOAP Action

  51. String soapAction = "http://WebXml.com.cn/getMobileCodeInfo";

  52. // 指定WebService的命名空間和調用的方法名

  53. SoapObject rpc = newSoapObject(nameSpace, methodName);

  54. // 設置需調用WebService接口需要傳入的兩個參數mobileCode、userId

  55. rpc.addProperty("mobileCode", phoneSec);

  56. rpc.addProperty("userId","");

  57. // 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本

  58. SoapSerializationEnvelope envelope = newSoapSerializationEnvelope(SoapEnvelope.VER10);

  59. envelope.bodyOut = rpc;

  60. // 設置是否調用的是dotNet開發的WebService

  61. envelope.dotNet = true;

  62. // 等價於envelope.bodyOut = rpc;

  63. envelope.setOutputSoapObject(rpc);

  64. HttpTransportSE transport = newHttpTransportSE(endPoint);

  65. try{

  66. // 調用WebService

  67. transport.call(soapAction, envelope);

  68. } catch(Exception e) {

  69. e.printStackTrace();

  70. }

  71. // 獲取返回的數據

  72. SoapObject object = (SoapObject) envelope.bodyIn;

  73. // 獲取返回的結果

  74. String result = object.getProperty(0).toString();

  75. // 將WebService返回的結果顯示在TextView中

  76. resultView.setText(result);

  77. }

  78. }

講解:
注意點1:如代碼中的62-69行所示,調用Web Service之前你需要先弄清楚這4個的值分別是什麼:命名空間、調用的方法名稱、EndPoint和SOAP Action。當在瀏覽器中訪問WSDL時,很容易得知命名空間、調用的方法名稱是什麼(不明白的請看上篇文章),至於EndPoint通常是將WSDL地址末尾的"?wsdl"去除後剩餘的部分;而SOAP Action通常爲命名空間 + 調用的方法名稱。
注意點2:75-76行是設置調用WebService接口方法需要傳入的參數。(在WSDL中能夠看到調用方法需要傳入的參數個數及參數名稱,在設置參數時最好指明每一個傳入參數的名稱,如本例中的mobileCode、userId。網上有些資料說在需要傳入多個參數時,只要多個參數的順序與WSDL中參數出現的順序一致即可,名稱並不需要和WSDL中的一致,但實際測試發現,大多數情況下並不可行!
例如下面圖版上顯示的WSDL片段,調用該Web Service的checkUserInfo方法就需要傳入4個參數,參數名稱分別爲:in0、in1、in2和in3。
0_1305783129bZ95.gif

注意點3也許你會對第100行代碼產生疑惑,爲什麼要用object.getProperty("getMobileCodeInfoResult")來取得調用結果?那是因爲WSDL中明確告訴了返回結果是String數組,它的名稱爲getDatabaseInfoResult,WSDL中的描述如下:
<s:elementminOccurs="0"maxOccurs="1"name="getDatabaseInfoResult"type="tns:ArrayOfString"/>
本例中調用WebService後返回的結果如下所示:
<?xml version="1.0" encoding="utf-8"?>
<stringxmlns="http://WebXml.com.cn/">1398547:貴州貴陽 貴州移動黔中游卡</string>
咦,這裏明明返回的是xml格式的內容,爲什麼我們不需要通過解析xml來獲取我們需要的內容呢?其實如果你仔細看代碼中的96-97行並不難發現:
// 獲取返回的數據
SoapObject object = (SoapObject) envelope.bodyIn;

ksoap2能夠將返回的xml轉換成SoapObject對象,然後我們就可以通過操作對象的方式來獲取需要的數據了。
注意點4同樣還是第100行代碼。從有些WSDL中我們並不能得知返回結果的名稱(如本例中的getMobileCodeInfoResult),那又該如何調用呢?其實上面已經暗示了這個問題:當通過第97行代碼獲取返回結果並將其轉換成SoapObject對象後,如果你並不知道通過該對象的哪個屬性來取值,你完全可以調用對象的toString()方法來查看返回的內容,例如將本例中的第100行代碼替換成:
// 獲取返回的結果
String result = object.toString();

這樣得到的返回結果爲:
0_1305653792jZjU.gif
注意看括號{}裏面的內容是一個鍵-值對形式,以等號=分隔,我們正是通過=號左邊的“getMobileCodeInfoResult”來獲取右邊的查詢結果。
其實在不知道返回結果名稱時(如本例的100行,我們並不知道返回結果中有屬性getMobileCodeInfoResult),有一種更爲簡便的方法,直接通過索引下標來獲取屬性值,也就是將第100行代碼替換爲:
String result = object.getProperty(0).toString();
注意點5:本例中只返回了一個值,但有些WebService會返回多個值該怎麼獲取?獲取方法與本例完全一樣,只是需要注意的是如果是返回多個值,通過第100代碼object.getProperty(0);得到的可能仍然是一個SoapObject。不斷地調用getProperty()方法;總能得到你想要的全部結果。
注意點6:在調用某些WebService時,可能會報一些異常,但你又發現除了調用的WebService不同之外,其它地方的寫法和我的完全一樣,這又該如何解決呢?嘗試改變第79代碼中SOAP的版本號,可以分別嘗試使用SoapEnvelope.VER10、SoapEnvelope.VER11、SoapEnvelope.VER12這樣三個值。另外,在調用某些WebService時,可能在第91行代碼中,調用WebService時並不需要傳入soapAction,將其置爲null即可。
4)在AndroidManifest.xml中配置添加訪問網絡的權限(千萬別忘記!!!)

  1. <?xmlversion="1.0"encoding="utf-8"?>

  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"

  3. package="com.liufeng.ws.activity"

  4. android:versionCode="1"

  5. android:versionName="1.0">

  6. <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">

  7. <activityandroid:name=".MainActivity"android:label="@string/app_name">

  8. <intent-filter>

  9. <actionandroid:name="android.intent.action.MAIN"/>

  10. <categoryandroid:name="android.intent.category.LAUNCHER"/>

  11. </intent-filter>

  12. </activity>

  13. </application>

  14. <uses-sdkandroid:minSdkVersion="4"/>

  15. <!-- 訪問網絡的權限 -->

  16. <uses-permissionandroid:name="android.permission.INTERNET"/>

  17. </manifest>

5)運行結果
0_1305650829oF9K.gif


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章