如何在android中调用数据库的soap webservice

时间:2013-11-08 10:13:05

标签: android web-services soap

如何在android中为数据库调用soap的web服务。

我的Web服务在C#中的ASP.NET中。

为什么NewDataSet和Table值没有显示在android中的soap web服务中 请回答。

$ package com.example.asp_qrcode;

import java.util.Hashtable;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView output;
EditText treeid;
Button ok;
String s;
     private final String NAMESPACE = "tempuri.org/";
    private final String URL = "http://cafe-wb.com/QRCODE/service1.asmx";
    private final String SOAP_ACTION = "http://tempuri.org/SP_GET_TREE_NAME_BY_TREEID";
    private final String METHOD_NAME = "SP_GET_TREE_NAME_BY_TREEID";
    String resultString;
    SoapObject response;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    output = (TextView)findViewById(R.id.text2);
    treeid = (EditText)findViewById(R.id.editText1);
    ok = (Button)findViewById(R.id.button1);



    ///////////////////////////////////////////////////////////

    ok.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Thread thread = new Thread(){

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    s = treeid.getText().toString();

                    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
                    PropertyInfo treeIDProp =new PropertyInfo();
                    treeIDProp.setName("TREE_ID");
                    treeIDProp.setValue(s);
                    treeIDProp.setType(int.class);
                    request.addProperty(treeIDProp);


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

                    //Log.i("Envelop: ",);

                    try {
                        //androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        androidHttpTransport.debug=true;
                        androidHttpTransport.call(SOAP_ACTION, envelope);

                        response=(SoapObject) envelope.getResponse();
                        //response = (SoapObject)envelope.getResponse();
                       resultString= androidHttpTransport.responseDump;

                      //  resultString = response.toString();

                        //resultString = ((SoapObject)response.getPropertySafely("sequence")).getPropertySafely("element").toString(); 

                        //SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
                        Log.i("Result: ",resultString);

                        MainActivity.this.runOnUiThread(new Runnable() {
                            public void run() {

                                output.setText(resultString);

                           }
                       });          



                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            };

            thread.start();

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

我的网络服务结果是:

<DataSet xmlns="http://tempuri.org/">
<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"       xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Table">
<xs:complexType>
<xs:sequence>
<xs:element name="TREE_ID" type="xs:int" minOccurs="0"/>
<xs:element name="PARENT_ID" type="xs:int" minOccurs="0"/>
<xs:element name="TREE_NAME" type="xs:string" minOccurs="0"/>
<xs:element name="TYPE" type="xs:string" minOccurs="0"/>
<xs:element name="DISCRIPTION" type="xs:string" minOccurs="0"/>
<xs:element name="DATE_ADDED" type="xs:dateTime" minOccurs="0"/>
<xs:element name="Page" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"    xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<Table diffgr:id="Table1" msdata:rowOrder="0">
<TREE_ID>56</TREE_ID>
<PARENT_ID>41</PARENT_ID>
<TREE_NAME>P.T.F.E Envelope Gaskets</TREE_NAME>
<TYPE>P.T.F.E GASKETS</TYPE>
<DISCRIPTION>
<p><strong>PTFE Envelope Gaskets</strong>&nbsp;provided by us are largely used in various industries in different processes and purposes. We offer these PTFE Envelope Gaskets in two types namely Milled type and slit type. These gaskets can have inserts of CAF, Rubber, Corrugated steel sandwiched between CAF rings, PVC. The clients can avail the PTFE Envelope Gaskets manufactured by us in varied specifications, shapes, and sizes as per their requirements.</p> <p>&nbsp;</p> <p><strong>&nbsp;</strong></p> <p><strong>&nbsp;</strong></p> <p><strong>&nbsp;</strong></p> <p><strong>Milled Type</strong></p> <ul> <li>It is made to fit the insert and presents a flat face to the flange</li> <li>Fused End envelopes are being manufactured from Diameters of 400mm to any size with a maximum wall thickness of upto 100mm</li> </ul> <p><br /> <strong>Slit Type</strong></p> <ul> <li>The envelope in this variety does not present a full face to the flange</li> </ul> <p>It is perfectly adequate for varied applications&nbsp;</p>
</DISCRIPTION>
<DATE_ADDED>2013-06-10T13:54:56.41+05:30</DATE_ADDED>
<Page>1</Page>
</Table>
</NewDataSet>
</diffgr:diffgram>
</DataSet>

1 个答案:

答案 0 :(得分:1)

好的..首先,当您为网络侧或服务器端进行编码时使用 AsynTask

的好习惯

所以我告诉你如何正确地执行你的代码。

public class ExampleClass extends Activity {

    SoapObject result;

    SoapSerializationEnvelope envelope_test = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);

    Button btn_callService;
    HttpTransportSE androidHttpTransport;


    public String NAMESPACE = "tempuri.org/";
    public  String URL = "http://cafe-wb.com/QRCODE/service1.asmx";
    public  String SOAP_ACTION = "http://tempuri.org/SP_GET_TREE_NAME_BY_TREEID";
    public  String METHOD_NAME = "SP_GET_TREE_NAME_BY_TREEID";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    setContentView(R.layout.absence);
     btn_callService= (Button) findViewById(R.id.Approve1);
}


    @Override
    protected void onStart() {

        btn_callService.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                    new ShowDialogAsyncTask ().execute();   

        });

        super.onStart();

    }



    public class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void> {
        ProgressDialog dialog = new ProgressDialog(ExampleClass.this);

        @Override
        protected void onPreExecute() {
            // update the UI immediately after the task is executed
            dialog.setMessage("Please wait...");
            dialog.setCancelable(false);
            dialog.show();

            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            callingNotificationDet(envelope_test);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
            try {
                dialog.dismiss();
            } catch (Exception e) {
                // TODO: handle exception
            }

            retrieveNotificationDet(envelope_test);

        }
        public void callingNotificationDet(SoapSerializationEnvelope envelope){



        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        request.addProperty("TREE_ID",""+s); //( s = treeid.getText().toString();) set your property here
        request.addProperty(); // set your property here

        // create header
        Element[] header = new Element[1];
        header[0] = new Element()
                .createElement(
                        "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                        "Security");
        header[0].setAttribute(null, "mustUnderstand", "1");

        Element usernametoken = new Element()
                .createElement(
                        "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                        "UsernameToken");
        usernametoken.setAttribute(null, "Id", "UsernameToken-1");
        header[0].addChild(Node.ELEMENT, usernametoken);

        Element username = new Element().createElement(null, "n0:Username");
        username.addChild(Node.IGNORABLE_WHITESPACE, userName);
        usernametoken.addChild(Node.ELEMENT, username);

        Element pass = new Element().createElement(null, "n0:Password");
        pass.setAttribute(
                null,
                "Type",
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
        pass.addChild(Node.TEXT, password);
        usernametoken.addChild(Node.ELEMENT, pass);

        // add header to envelope
        envelope.headerOut = header;
        envelope.dotNet = true;
        envelope.bodyOut = request;

        androidHttpTransport = new HttpTransportSE(URL, 30000);
        envelope.setOutputSoapObject(request);
        try {
            androidHttpTransport.debug = true;
            androidHttpTransport.call(SOAP_ACTION, envelope); // Calling

        } catch (SoapFault e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
  public void retrieveAction(SoapSerializationEnvelope envelope)
{
    SoapObject result;
    try {
        result = (SoapObject) envelope.getResponse();
    }
    catch (ClassCastException e) {
        result = (SoapObject) envelope.bodyIn;
        String res = result.getPropertyAsString(0).toString();

    }
    catch (SoapFault e) {

    }

}
    }

}   

确定您的所有NameSpace,方法名称.URL是正确的