糾正網上亂傳的android調用Webservice方法。,androidwebservice

來源:互聯網
上載者:User

糾正網上亂傳的android調用Webservice方法。,androidwebservice

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>

  運行效果如:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.