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

1.寫做背景:android

  筆者想實現android調用webservice,但是網上全是無論對與錯亂轉載的文章,結果不但不能解決問題,只會讓人心煩,因此筆者決定將本身整理好的能用的android調用webservice的實現分享給你們,供之後遇到相同需求的人能少走彎路。git

  源碼使用android studio編寫,能夠在github上面下載觀看:https://github.com/jhscpang/TestWebSwervicegithub

 

2.具體實現:web

  本文的重點是android怎麼調用webservice而不是用哪一個webservice,因此這裏就用網上傳的比較多的計算來電歸屬地的webservice進行測試。這個webservice地址爲:http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl。瀏覽器

用瀏覽器訪問這個網址能夠看到以下界面:app

圖中被圈起來的部分1說明soap版本爲12, 被圈起來的部分2說明了namespace地址,這兩個值稍後在代碼中能用到。異步

圖中被圈起來的部分說明了調用的方法的名字,裏面的說明文檔告訴了輸入參數和返回值等信息,這些信息稍後代碼中也會用到。ide

 

  下面寫請求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>

  運行效果以下圖:

相關文章
相關標籤/搜索