如何在android中使用kso​​ap解析调用方法时发送参数

时间:2013-09-20 04:29:45

标签: android android-intent ksoap2

我正在进行基于SOAP的解析。当方法中没有参数时,我能够获得响应。但是现在我正在调用具有一些参数并返回一个对象的函数。虽然我正在尝试获取null。我正在调用此功能 getDestinationStationDashboard ,参数为“HNH”

这是我的代码。

package com.example.soapbased;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class Soapclass extends Activity {
    private static final String SOAP_ACTION = "http://wsendpoints.bbrailapps.firstgroup.com/getDestinationStationDashboard";
    private static final String METHOD_NAME = "getDestinationStationDashboard";
    private static final String NAMESPACE = "http://wsendpoints.bbrailapps.firstgroup.com";
    private static final String URL = "http://railapps.firstgroup.com/FirstGroupRailApps/services/RailAppsCAWS?wsdl";
    private SoapObject resultRequestSOAP = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_soapclass);
        System.out.println("=====================" + haveNetworkConnection());

        new AsyncTask<Void, Void, Object>() {
            ProgressDialog dialog = new ProgressDialog(Soapclass.this);
            private PropertyInfo pi1;

            protected void onPreExecute() {
                dialog.show();
            };

            protected Object doInBackground(Void[] params) {

                /*resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);

                SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envp.dotNet = true;
                envp.setOutputSoapObject(resultRequestSOAP);
                AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
                        URL);
                try {
                    androidHttpTransport.call(SOAP_ACTION, envp);
                    SoapPrimitive resultsString = (SoapPrimitive)envp.getResponse();
                    System.out.println("resultsString"+resultsString);
                    return resultsString.toString();

                } catch (Exception e) {
 System.out.println("---------------------------"+e.toString());
 Log.d("ppp", e.toString());
                    Toast.makeText(Soapclass.this,
                            "Check Network connectivety" + e.toString(),
                            Toast.LENGTH_LONG).show();
                    Log.v("WS Error->", e.toString());
                    return e.toString();
                }*/

                 resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);
                 pi1 = new PropertyInfo();
                 pi1.setName("crsCode");
                 pi1.setValue("HNH");//get the string that is to be sent to the web service
                 pi1.setType(String.class);
                 resultRequestSOAP.addProperty(pi1);
                SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envp.dotNet = true;
                envp.setOutputSoapObject(resultRequestSOAP);
                AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
                        URL);
                try {
                    androidHttpTransport.call(SOAP_ACTION, envp);
                    SoapPrimitive resultsString = (SoapPrimitive)envp.getResponse();
                    System.out.println("resultsString"+resultsString);
                    return resultsString;

                } catch (Exception e) {
 System.out.println("---------------------------"+e.toString());
 Log.d("ppp", e.toString());
                    Toast.makeText(Soapclass.this,
                            "Check Network connectivety" + e.toString(),
                            Toast.LENGTH_LONG).show();
                    Log.v("WS Error->", e.toString());
                    return e.toString();
                }


            };

            protected void onPostExecute(String result) {
                dialog.dismiss();
                Toast.makeText(Soapclass.this,
                        "Check Network connectivety" + result,
                       Toast.LENGTH_LONG).show();
            };
        }.execute();

    }

    public boolean haveNetworkConnection() {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

}

改变后我得到了这个对象 我得到这个SoapObject obj =(SoapObject)envp.getResponse();                     的System.out.println( “resultsString” + OBJ);

resultsStringanyType{RID=201309201377618; alertDetailPopulated=true; alertsId=0; alertsSummary=anyType{}; destExpArrival=06:31; destSchArrival=06:30; destinationStation=anyType{crsCode=BKJ; stationName=Beckenham Junction; }; expArrival=06:19; expDepart=06:20; otherAlertPresent=false; platformNo=3; routeDetailPopulated=false; routeDetails=null; rsID=null; schArrival=06:19; schDepart=06:19; serviceAlertPresent=false; toc=SE; tocName=Southeastern; trainID=2M06; trainLastReportedAt=null; }

现在如何从这个对象打印RID或其他东西。

4 个答案:

答案 0 :(得分:1)

public class MainActivity extends Activity {
    private static final String SOAP_ACTION = "http://wsendpoints.bbrailapps.firstgroup.com/getDestinationStationDashboard";
    private static final String METHOD_NAME = "getDestinationStationDashboard";
    private static final String NAMESPACE = "http://wsendpoints.bbrailapps.firstgroup.com";
    private static final String API_URL = "http://railapps.firstgroup.com/FirstGroupRailApps/services/RailAppsCAWS?wsdl";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadSoap().execute();
    }

    private void doNetwork() {
        SoapObject resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);
        PropertyInfo pi1 = new PropertyInfo();
        pi1.setName("crsCode");
        pi1.setValue("HNH");
        pi1.setType(PropertyInfo.STRING_CLASS);
        resultRequestSOAP.addProperty(pi1);
        SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envp.dotNet = true;
        try {
            envp.setOutputSoapObject(resultRequestSOAP);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(API_URL);
            androidHttpTransport.debug = true;
            androidHttpTransport.call(SOAP_ACTION, envp);
            System.out.println(androidHttpTransport.requestDump);
            System.out.println(androidHttpTransport.responseDump);
            SoapObject response = (SoapObject) envp.getResponse();
            System.out.println("resultsString" + response.toString());

        } catch (Exception e) {

        }

    }

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

    public class DownloadSoap extends AsyncTask<Void, Void, Void> {
        private ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(MainActivity.this);
            pd.setMessage("Fetching Data");
            pd.setIndeterminate(true);
            pd.setCancelable(false);
            pd.show();
        }
        @Override
        protected Void doInBackground(Void... params) {
            doNetwork();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            pd.dismiss();
        }
    }

}

它为我工作,但需要花费大量时间来获取数据。

我得到的回复如下: -

09-20 12:22:39.974: I/System.out(2421): <?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><getDestinationStationDashboardResponse 
xmlns="http://wsendpoints.bbrailapps.firstgroup.com"><getDestinationStationDashboardReturn><RID>201309201377851</RID><alertDetailPopulated>false</alertDetailPopulated>
<alertsId>0</alertsId><alertsSummary xsi:nil="true"/><destExpArrival>08:15</destExpArrival><destSchArrival>08:15</destSchArrival><destinationStation><crsCode>BKJ</crsCode>
<stationName>Beckenham Junction</stationName></destinationStation><expArrival>08:04</expArrival><expDepart>08:04</expDepart><otherAlertPresent>false</otherAlertPresent>
<platformNo>3</platformNo><routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/><rsID xsi:nil="true"/><schArrival>08:04</schArrival><schDepart>08:04</schDepart>
<serviceAlertPresent>false</serviceAlertPresent><toc>SE</toc><tocName>Southeastern</tocName><trainID>2M20</trainID><trainLastReportedAt xsi:nil="true"/></getDestinationStationDashboardReturn>
<getDestinationStationDashboardReturn><RID>201309201377886</RID><alertDetailPopulated>false</alertDetailPopulated><alertsId>0</alertsId><alertsSummary xsi:nil="true"/>
<destExpArrival>08:30</destExpArrival><destSchArrival>08:30</destSchArrival><destinationStation><crsCode>BKJ</crsCode><stationName>Beckenham Junction</stationName>
</destinationStation><expArrival>08:19</expArrival><expDepart>08:19</expDepart><otherAlertPresent>false</otherAlertPresent><platformNo>3</platformNo>
<routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/><rsID xsi:nil="true"/><schArrival>08:19</schArrival><schDepart>08:19</schDepart>
<serviceAlertPresent>false</serviceAlertPresent><toc>SE</toc><tocName>Southeastern</tocName><trainID>2M22</trainID><trainLastReportedAt xsi:nil="true"/>
</getDestinationStationDashboardReturn><getDestinationStationDashboardReturn><RID>201309201377085</RID><alertDetailPopulated>false</alertDetailPopulated>
<alertsId>0</alertsId><alertsSummary xsi:nil="true"/><destExpArrival>09:38</destExpArrival><destSchArrival>09:38</destSchArrival><destinationStation>
<crsCode>BDM</crsCode><stationName>Bedford</stationName></destinationStation><expArrival>08:12</expArrival><expDepart>08:13</expDepart>
<otherAlertPresent>false</otherAlertPresent><platformNo>2</platformNo><routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/>
<rsID xsi:nil="true"/><schArrival>08:12</schArrival><schDepart>08:13</schDepart><serviceAlertPresent>false</serviceAlertPresent>
<toc>SE</toc><tocName>Southeastern</tocName><trainID>1G65</trainID><trainLastReportedAt xsi:nil="true"/></getDestinationStationDashboardReturn>
<getDestinationStationDashboardReturn><RID>201309201386846</RID><alertDetailPopulated>false</alertDetailPopulated><alertsId>0</alertsId>
<alertsSummary xsi:nil="true"/><destExpArrival>10:08</destExpArrival><destSchArrival>10:08</destSchArrival><destinationStation>
<crsCode>BDM</crsCode><stationName>Bedford</stationName></destinationStation><expArrival>08:41</expArrival>
<expDepart>08:41</expDepart><otherAlertPresent>false</otherAlertPresent><platformNo>1</platformNo>
<routeDetailPopulated>false</routeDetailPopulated><routeDetails xsi:nil="true"/><rsID xsi:nil="true"/>
<schArrival>08:41</schArrival><schDepart>08:41</schDepart><serviceAlertPresent>false</serviceAlertPresent>
<toc>FC</toc><tocName>First Capital Connect</tocName><trainID>2W70</trainID><trainLastReportedAt>Train last reported at : Haywards Heath</trainLastReportedAt>
</getDestinationStationDashboardReturn><getDestinationStationDashboardReturn><RID>201309201377851</RID><alertDetailPopulated>false</alertDetailPopulated>
<alertsId>0</alertsId><alertsSummary xsi:nil="true"/><destExpArrival>08:24</destExpArrival><destSchArrival>08:24</destSchArrival><destinationStation>
<crsCode>BKL</crsCode><stationName>Bickley</stationName></destinationStation><expArrival>08:04</expArrival><expDepart>08:04</exp

希望这会对你有所帮助。


使用此类的帮助解析Soap Response的最简单方法 创建一个类名SoapResponseParser

public class SoapResponseParser {


    public static void parseBusinessObject(String input, Object output)
            throws NumberFormatException, IllegalArgumentException,
            IllegalAccessException, InstantiationException {

        @SuppressWarnings("rawtypes")
        Class theClass = output.getClass();
        Field[] fields = theClass.getDeclaredFields();

        for (int i = 0; i < fields.length; i++) {
            Type type = fields[i].getType();
            fields[i].setAccessible(true);

            // detect String
            if (fields[i].getType().equals(String.class)) {
                String tag = fields[i].getName() + "=";

                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        if (strValue.contains("anyType")) {
                            fields[i].set(output, "-");
                        } else
                            fields[i].set(output, strValue);
                    }
                }
            }

            // detect int or Integer
            if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
                String tag = fields[i].getName() + "=";

                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        fields[i].setInt(output, Integer.valueOf(strValue));
                    }
                }
            }

            // detect float or Float
            if (type.equals(Float.TYPE) || type.equals(Float.class)) {
                String tag = fields[i].getName() + "=";
                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        fields[i].setFloat(output, Float.valueOf(strValue));
                    }
                }
            }
            // detect double or Double
            if (type.equals(Double.TYPE) || type.equals(Double.class)) {
                String tag = fields[i].getName() + "=";
                if (input.contains(tag)) {
                    String strValue = input.substring(
                            input.indexOf(tag) + tag.length(),
                            input.indexOf(";", input.indexOf(tag)));
                    if (strValue.length() != 0) {
                        fields[i].setDouble(output, Double.valueOf(strValue));
                    }
                }
            }
         }      
      }
}

编辑了doNetwork()方法

private void doNetwork() {
        SoapObject resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);
        PropertyInfo pi1 = new PropertyInfo();
        pi1.setName("crsCode");
        pi1.setValue("HNH");
        pi1.setType(PropertyInfo.STRING_CLASS);
        resultRequestSOAP.addProperty(pi1);
        SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envp.dotNet = true;
        try {
            envp.setOutputSoapObject(resultRequestSOAP);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(API_URL);
            androidHttpTransport.debug = true;
            androidHttpTransport.call(SOAP_ACTION, envp);
            System.out.println(androidHttpTransport.requestDump);
            System.out.println(androidHttpTransport.responseDump);
            SoapObject response = (SoapObject) envp.getResponse();
            GetDestinationStationDashboardReturn destination= new GetDestinationStationDashboardReturn();
            System.out.println("resultsString" + response.toString());
            SoapResponseParser.parseBusinessObject(response.toString(),
                    destination);
            System.out.println(destination.getRID()+"  "+destination.getAlertDetailPopulated()+" "+destination.getAlertsId());

        } catch (Exception e) {

        }

    }

现在我解释了如何解析,现在由您决定如何实现您的要求。 快乐的编码。


创建一个类GetDestinationStationDashboardReturn

public class GetDestinationStationDashboardReturn {
    private String RID;
    private String alertDetailPopulated;
    private String alertsId;
    private String destExpArrival;
    private String destSchArrival;
    public String getRID() {
        return RID;
    }
    public void setRID(String rID) {
        RID = rID;
    }
    public String getAlertDetailPopulated() {
        return alertDetailPopulated;
    }
    public void setAlertDetailPopulated(String alertDetailPopulated) {
        this.alertDetailPopulated = alertDetailPopulated;
    }
    public String getAlertsId() {
        return alertsId;
    }
    public void setAlertsId(String alertsId) {
        this.alertsId = alertsId;
    }
    public String getDestExpArrival() {
        return destExpArrival;
    }
    public void setDestExpArrival(String destExpArrival) {
        this.destExpArrival = destExpArrival;
    }
    public String getDestSchArrival() {
        return destSchArrival;
    }
    public void setDestSchArrival(String destSchArrival) {
        this.destSchArrival = destSchArrival;
    }

}

答案 1 :(得分:0)

试试这个:

 resultRequestSOAP     = new SoapObject(NAMESPACE, METHOD_NAME);
 PropertyInfo UserName = new PropertyInfo();
 resultRequestSOAP.addProperty(UserName);

如果你想添加另一个参数,那么你必须创建PropertyInfo的单独对象,如下所示:

 resultRequestSOAP      = new SoapObject(NAMESPACE, METHOD_NAME);

 PropertyInfo UserName  = new PropertyInfo();
 PropertyInfo UserEmail = new PropertyInfo();

 resultRequestSOAP.addProperty(UserName);
 resultRequestSOAP.addProperty(UserEmail);

答案 2 :(得分:0)

你喜欢这样使用。

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

   request.addProperty("crsCode","HNH");

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

  HttpTransportSE ht = new HttpTransportSE(URL);

try {
  ht.call(SOAP_ACTION, envelope);
  final SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
 str = response.toString();
} 

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

 Log.d("WebRespone", str);
 return str;

希望这会对你有所帮助。为您的reference

答案 3 :(得分:0)

private static final String SOAP_ACTION = "http://wsendpoints.bbrailapps.firstgroup.com/getDestinationStationDashboard";
    private static final String METHOD_NAME = "getDestinationStationDashboard";
    private static final String NAMESPACE = "http://wsendpoints.bbrailapps.firstgroup.com";
    private static final String URL = "http://railapps.firstgroup.com/FirstGroupRailApps/services/RailAppsCAWS?wsdl";
        SOAP_ACTION = SOAP_ACTION + METHOD_NAME;
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        // Use this to add parameters
        request.addProperty("crsCode", HNS);
        String SoapResult = null;
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);

    envelope.setOutputSoapObject(request);

    envelope.dotNet = true;

    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    // this is the actual part that will call the webservice
    androidHttpTransport.call(SOAP_ACTION, envelope);

    // Get the SoapResult from the envelope body.
    if (envelope.bodyIn instanceof SoapFault) {
        SoapResult = ((SoapFault) envelope.bodyIn).faultstring;
    } else {
        SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
        SoapResult = resultsRequestSOAP.getProperty(0).toString();
    }

    Log.i(WebCalls, "Response " + SoapResult);

我希望它对你有用。