(轉)Android訪問webservice 糾正網上亂傳的android呼叫Webservice方法。
糾正網上亂傳的android呼叫Webservice方法。
1.寫作背景:
筆者想實現android呼叫webservice,可是網上全是不管對與錯亂轉載的文章,結果不但不能解決問題,只會讓人心煩,所以筆者決定將自己整理好的能用的android呼叫webservice的實現分享給大家,供以後遇到相同需求的人能少走彎路。
原始碼使用android studio編寫,可以在github上面下載觀看:https://github.com/jhscpang/TestWebSwervice。
2.具體實現:
本文的重點是android怎麼呼叫webservice而不是用哪個webservice,所以這裡就用網上傳的比較多的計算來電歸屬地的webservice進行測試。這個webservice地址為:http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl。
用瀏覽器訪問這個網址可以看到如下介面:
圖中被圈起來的部分1說明soap版本為12, 被圈起來的部分2說明了namespace地址,這兩個值稍後在程式碼中能用到。
圖中被圈起來的部分說明了呼叫的方法的名字,裡面的說明文件告訴了輸入引數和返回值等資訊,這些資訊稍後程式碼中也會用到。
下面寫請求webservice的方法,程式碼如下, 具體每句的解釋有備註:
/**
* 手機號段歸屬地查詢
*
* @param phoneSec 手機號段
*/
public String getRemoteInfo(String phoneSec) throws Exception{
String WSDL_URI = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL";//wsdl 的uri
String namespace = "http://WebXml.com.cn/";//namespace
String methodName = "getMobileCodeInfo";//要呼叫的方法名稱
SoapObject request = new SoapObject(namespace, methodName);
// 設定需呼叫WebService介面需要傳入的兩個引數mobileCode、userId
request.addProperty("mobileCode", phoneSec);
request.addProperty("userId", "");
//建立SoapSerializationEnvelope 物件,同時指定soap版本號(之前在wsdl中看到的)
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER12);
envelope.bodyOut = request;//由於是傳送請求,所以是設定bodyOut
envelope.dotNet = true;//由於是.net開發的webservice,所以這裡要設定為true
HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
httpTransportSE.call(null, envelope);//呼叫
// 獲取返回的資料
SoapObject object = (SoapObject) envelope.bodyIn;
// 獲取返回的結果
result = object.getProperty(0).toString();
Log.d("debug",result);
return result;
}
因為呼叫webservice屬於聯網操作,因此不能再UI執行緒中執行訪問webservice,為了便於將結果反饋給UI執行緒,採用AsyncTask執行緒,程式碼如下:
class QueryAddressTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
// 查詢手機號碼(段)資訊*/
try {
result = getRemoteInfo(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
//將結果返回給onPostExecute方法
return result;
}
@Override
//此方法可以在主執行緒改變UI
protected void onPostExecute(String result) {
// 將WebService返回的結果顯示在TextView中
resultView.setText(result);
}
}
然後在主執行緒中給使用者設定使用該功能的方法,程式碼如下:
private EditText phoneSecEditText; private TextView resultView; private Button queryButton; private String result; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); 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; } //啟動後臺非同步執行緒進行連線webService操作,並且根據返回結果在主執行緒中改變UI QueryAddressTask queryAddressTask = new QueryAddressTask(); //啟動後臺任務 queryAddressTask.execute(phoneSec); } }); }
佈局檔案如下:
<?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>
AndroidManifest檔案如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jhsc.testwebservice" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
執行效果如下圖:
soap協議jar包下載
2.54版本:ksoap2-android 2.54.jar
http://www.runoob.com/try/download/ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar
3.30版本:ksoap2-android 3.30.jar
http://www.runoob.com/try/download/ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar
轉自:https://www.cnblogs.com/superpang/p/4911422.html
1.寫作背景:
筆者想實現android呼叫webservice,可是網上全是不管對與錯亂轉載的文章,結果不但不能解決問題,只會讓人心煩,所以筆者決定將自己整理好的能用的android呼叫webservice的實現分享給大家,供以後遇到相同需求的人能少走彎路。
原始碼使用android studio編寫,可以在github上面下載觀看:https://github.com/jhscpang/TestWebSwervice。
2.具體實現:
本文的重點是android怎麼呼叫webservice而不是用哪個webservice,所以這裡就用網上傳的比較多的計算來電歸屬地的webservice進行測試。這個webservice地址為:http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl。
用瀏覽器訪問這個網址可以看到如下介面:
圖中被圈起來的部分1說明soap版本為12, 被圈起來的部分2說明了namespace地址,這兩個值稍後在程式碼中能用到。
圖中被圈起來的部分說明了呼叫的方法的名字,裡面的說明文件告訴了輸入引數和返回值等資訊,這些資訊稍後程式碼中也會用到。
下面寫請求webservice的方法,程式碼如下, 具體每句的解釋有備註:
/**
* 手機號段歸屬地查詢
*
* @param phoneSec 手機號段
*/
public String getRemoteInfo(String phoneSec) throws Exception{
String WSDL_URI = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL";//wsdl 的uri
String namespace = "http://WebXml.com.cn/";//namespace
String methodName = "getMobileCodeInfo";//要呼叫的方法名稱
SoapObject request = new SoapObject(namespace, methodName);
// 設定需呼叫WebService介面需要傳入的兩個引數mobileCode、userId
request.addProperty("mobileCode", phoneSec);
request.addProperty("userId", "");
//建立SoapSerializationEnvelope 物件,同時指定soap版本號(之前在wsdl中看到的)
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER12);
envelope.bodyOut = request;//由於是傳送請求,所以是設定bodyOut
envelope.dotNet = true;//由於是.net開發的webservice,所以這裡要設定為true
HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
httpTransportSE.call(null, envelope);//呼叫
// 獲取返回的資料
SoapObject object = (SoapObject) envelope.bodyIn;
// 獲取返回的結果
result = object.getProperty(0).toString();
Log.d("debug",result);
return result;
}
因為呼叫webservice屬於聯網操作,因此不能再UI執行緒中執行訪問webservice,為了便於將結果反饋給UI執行緒,採用AsyncTask執行緒,程式碼如下:
class QueryAddressTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
// 查詢手機號碼(段)資訊*/
try {
result = getRemoteInfo(params[0]);
} catch (Exception e) {
e.printStackTrace();
}
//將結果返回給onPostExecute方法
return result;
}
@Override
//此方法可以在主執行緒改變UI
protected void onPostExecute(String result) {
// 將WebService返回的結果顯示在TextView中
resultView.setText(result);
}
}
然後在主執行緒中給使用者設定使用該功能的方法,程式碼如下:
private EditText phoneSecEditText; private TextView resultView; private Button queryButton; private String result; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); 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; } //啟動後臺非同步執行緒進行連線webService操作,並且根據返回結果在主執行緒中改變UI QueryAddressTask queryAddressTask = new QueryAddressTask(); //啟動後臺任務 queryAddressTask.execute(phoneSec); } }); }
佈局檔案如下:
<?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>
AndroidManifest檔案如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jhsc.testwebservice" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
執行效果如下圖:
soap協議jar包下載
2.54版本:ksoap2-android 2.54.jar
http://www.runoob.com/try/download/ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar
3.30版本:ksoap2-android 3.30.jar
http://www.runoob.com/try/download/ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar
轉自:https://www.cnblogs.com/superpang/p/4911422.html