android與C# WebService基於ksoap通訊(Android篇)

來源:互聯網
上載者:User

標籤:android   web service   通訊   

1.建立安卓項目KSoapTest

2.一路Next
3.添加ksoap2-android-assembly-3.1.0-jar-with-dependencies.jar到項目
(稍後的完整項目下載後會包含這個jar包)
4.編輯 activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/textView1"        android:layout_marginTop="56dp"        android:text="點擊訪問服務端HelloWorld" />    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="86dp"        android:text="TextView" /></RelativeLayout>

5.添加基類Activity類:BaseKsoapActivity.java,代碼如下:

package com.example.base;import java.util.Iterator;import java.util.Map;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.os.AsyncTask;import android.os.Bundle;/** *  * @author WangPeng * 2015年8月7日11:24:49 * 整合該類的Activity可以方便的調用Web Service進行通訊 * */@SuppressWarnings("all")public abstract class BaseKsoapActivity extends Activity{    // 伺服器連結    final String WEB_SERVICE_URL = "http://%s/TestService.asmx?wsdl";    // 命名空間    final String Namespace = "http://tempuri.org/";    //伺服器位址    private String ipAddress;    /**     * Activity 建立時候執行     * 擷取Web Service所在伺服器位址     */    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //IP地址可以通過配置來獲得        //注意:不能使用127.0.0.1或localhost,因為安卓程式是在手機上啟動並執行,手機不能通過127.0.0.1或localhost訪問電腦上的IIS        //這裡我使用的是我電腦的無線網卡的IP地址,My Phone也串連在這個無線網上        this.ipAddress = "192.168.20.133";    }    /**     *      * @param paras     */    protected void Request(Object... paras) {        new AsyncTask<Object, Object, SoapObject>() {                       @Override            protected SoapObject doInBackground(Object... args) {                // 1、指定Web Service的命名空間和調用的方法名                String MethodName = (String) args[0];                SoapObject request = new SoapObject(Namespace, MethodName);                //2、設定調用傳遞的參數                Map<String, Object> paras = (Map<String, Object>) args[1];                // 2、設定調用方法的參數值,如果沒有參數,可以省略,                if (paras != null) {                    Iterator iter = paras.entrySet().iterator();                    while (iter.hasNext()) {                        Map.Entry entry = (Map.Entry) iter.next();                        request.addProperty((String) entry.getKey(), (String) entry.getValue());                    }                }                // 3、產生調用Web Service方法的SOAP請求資訊。該資訊由SoapSerializationEnvelope對象描述                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);                envelope.bodyOut = request;                // c#寫的應用程式必須加上這句                envelope.dotNet = true;                HttpTransportSE ht = new HttpTransportSE(String.format(WEB_SERVICE_URL, ipAddress));                // 使用call方法調用WebService方法                try {                    ht.call(null, envelope);                                    } catch (Exception e) {                    publishProgress("網路錯誤", "網路連接失敗,請檢查裝置是否處於連網狀態,並且已設定管理員地址。");                    return null;                }                try {                    SoapObject obj = (SoapObject) envelope.bodyIn;                    return obj;                } catch (Exception e) {                    publishProgress("網路錯誤", "伺服器端返回結果");                    return null;                }            }            @Override            protected void onPostExecute(SoapObject obj) {                super.onPostExecute(obj);                requestCallBack(obj);            }            @Override            protected void onProgressUpdate(Object... values) {                super.onProgressUpdate(values);                if (values != null && values.length == 2) {                    ShowMessage((String) values[0], (String) values[1]);                }            }        }.execute(paras);    }    protected void ShowMessage(String title, String msg) {        new AlertDialog.Builder(this).setTitle(title).setMessage(msg).setPositiveButton("OK", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {            }        }).show();    }    /**     * 所有繼承這個Activity的類都必須實現這個方法     * 每次通訊結束都會調用這個方法     *      * @param obj 和伺服器通訊得到的傳回值     */    protected abstract void requestCallBack(SoapObject obj);}

6.編輯MainActivity,繼承上面的BaseKsoapActivity,代碼如下:

package com.example.ksoaptest;import java.util.HashMap;import java.util.Map;import org.ksoap2.serialization.SoapObject;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import com.example.base.BaseKsoapActivity;public class MainActivity extends BaseKsoapActivity {    private Button btn;    private TextView tv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn = (Button)findViewById(R.id.button1);        tv = (TextView)findViewById(R.id.textView1);        btn.setOnClickListener(new OnClickListener() {                      @Override            public void onClick(View arg0) {                Map<String, Object> paras = new HashMap<String, Object>();                //paras.put("參數名","參數值");                Request("HelloWorld", paras);                           }        });    }    @Override    protected void requestCallBack(SoapObject obj) {        //複雜一點的傳回值需要解析,我們這裡返回的是String,所以解析比較簡單        //對於複雜的傳回型別,個人建議在服務端轉換成JSON字串後返回,        //這樣用戶端只要得到這個字串扔給第三方的Gson或jsonlib就可以轉換成需要的對象        //而且對於byte數組這樣的傳回值通過xml傳輸會加上很多無用的標籤,增加了傳輸的資料量,降低效率        tv.setText(obj.getProperty(0).toString());          }}

7.在AndroidManifest.xml添加網路許可權:

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

8.運行

9.C#和安卓完整代碼已上傳
http://download.csdn.net/detail/u013816347/8999889

歡迎評論指正

著作權聲明:本文為博主原創文章,轉載的時候請註明出處。

android與C# WebService基於ksoap通訊(Android篇)

聯繫我們

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