簡體   English   中英

使用kso​​ap使用android調用ASP.NET Web服務

[英]Call ASP.NET web service using android using ksoap

我為呼叫Web服務創建了一個簡單的類

public class CallSoap {
    public final String SOAP_ACTION = "http://tempuri.org/Add";

    public  final String OPERATION_NAME = "Add"; 

    public  final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

    public  final String SOAP_ADDRESS = "http://localhost:41614/Service1.asmx";
    public CallSoap() 
    { 
    }
    public String Call(int a,int b)
    {
    SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
    request.addProperty("a",a);
    request.addProperty("b",b);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);

    HttpTransport httpTransport = new HttpTransport(SOAP_ADDRESS);
    Object response=null;
    try
    {
    httpTransport.call(SOAP_ACTION, envelope);
    response = envelope.getResponse();
    }
    catch (Exception exception)
    {
    response=exception.toString();
    }
    return response.toString();
    }
}

這是我的“ Activity點擊方法

public void clickData(View v)
{
    //Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText et=(EditText) findViewById(R.id.editText1);
    EditText et2=(EditText) findViewById(R.id.editText2);
    TextView tv=(TextView) findViewById(R.id.textView1);

    int a=Integer.parseInt(et.getText().toString());
    int b=Integer.parseInt(et2.getText().toString()); 

    CallSoap cs=new CallSoap();
    tv.setText(cs.Call(a, b));
}

錯誤“不幸的是,App1已停止”。 請幫我..

這是由於Android 2.2之后出現NetworkOnMainThread異常,您無法在mainUi線程中運行長時間運行的操作(例如網絡訪問),因為mainUI線程用於加載Ui組件以使您的應用程序流暢高效。您應該使用AsynTask類來保持它脫離主線程

對於初學者來說,也是一種很好的實踐,將調用放入單獨的線程中。 我這樣做是這樣的:

public void call() {
    Log.d("TAG", "Started call");
    new Thread(new Runnable()
    {
        public void run() {
            Looper.prepare();

            /** UI stuff/ This runs on the main thread to update the UI. This can be used for displaying something like "please wait */

            AppPrefFragment.updateSyncJobsNumber(AppPrefFragment.JOB_START);
            if (AppPrefActivity.context != null) {
                ((Activity) AppPrefActivity.context).runOnUiThread(new Runnable()
                {
                    public void run() {
                        //AppPrefFragment.setSyncPreferenceStatusShowingOngoingJobs();
                        ... show "please wait"
                    }
                });
            }


            /** Actual stuff  that you want to do */

            ... the HttpCall or SOAP etc
        }
    }).start();
}

請注意,返回必須異步處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM